1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2025-01-03 01:22:21 +02:00

новый

This commit is contained in:
Nikitin Aleksandr 2023-09-28 17:45:44 +03:00
parent 0eacd63688
commit b7446dc946
763 changed files with 396603 additions and 0 deletions

16
.env_example Normal file
View File

@ -0,0 +1,16 @@
#filename file to create with .graphml extension
FILENAME_GRAPHML=
#table names have to image, regular expression format
INCLUDE_TABLES=
#table names have to not image, regular expression format
EXCLUDE_TABLES=
#database credentials
DB_HOST=
DB_NAME=
DB_SCHEME=
DB_PORT=
DB_USER=
DB_PASSWORD=

15
.gitignore vendored Normal file
View File

@ -0,0 +1,15 @@
/.env
/cover.out
/internal/v0/app/.env
.env
/.idea/
/bin/.env
/log.txt
.vscode
/bin/image_connections
/settings/connections_add.txt
/bin/settings/connections_add.txt
/database.graphml
/database.graphml0

52
Makefile Normal file
View File

@ -0,0 +1,52 @@
SERVICENAME=crud_generator
SERVICEURL=github.com/ManyakRus/$(SERVICENAME)
FILEMAIN=./internal/main.go
FILEAPP=./bin/$(SERVICENAME)
NEW_REPO=$(SERVICENAME)
run:
clear
go build -race -o $(FILEAPP) $(FILEMAIN)
# cd ./bin && \
./bin/app_race
mod:
clear
go get -u ./...
go mod tidy -compat=1.18
go mod vendor
go fmt ./...
build:
clear
go build -race -o $(FILEAPP) $(FILEMAIN)
cd ./cmd && \
./VersionToFile.py
cp $(FILEAPP) $(GOPATH)/bin
lint:
clear
go fmt ./...
golangci-lint run ./internal/v0/...
golangci-lint run ./pkg/v0/...
gocyclo -over 10 ./internal/v0
gocyclo -over 10 ./pkg/v0
gocritic check ./internal/v0/...
gocritic check ./pkg/v0/...
staticcheck ./internal/v0/...
staticcheck ./pkg/v0/...
run.test:
clear
go fmt ./...
go test -coverprofile cover.out ./internal/v0/app/...
go tool cover -func=cover.out
newrepo:
sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g' go.mod
find -name *.go -not -path "*/vendor/*"|xargs sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g'
graph:
clear
image_packages ./ docs/packages.graphml
conn:
clear
image_connections ./internal docs/connections.graphml $(SERVICENAME)

2
bin/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/app_race
/log.txt

1
bin/date.txt Normal file
View File

@ -0,0 +1 @@
2023-09-11 13:17:12.998

6
bin/start_with_log.sh Executable file
View File

@ -0,0 +1,6 @@
logfile=log.txt
echo press CTRL+C to stop app
echo log file: $logfile
script -q /dev/null -c ./crud_generator > $logfile

1
bin/subversion.txt Normal file
View File

@ -0,0 +1 @@
00130

1
bin/version.txt Normal file
View File

@ -0,0 +1 @@
v0

52
cmd/VersionToFile.py Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/python3
# Python script to create an empty file
# with current date as name.
# importing datetime module
from datetime import datetime
import os
# datetime.datetime.now() to get
# current date as filename.
# TimeNow = datetime.datetime.now()
FILESUBVERSION="../bin/subversion.txt"
FILEDATE="../bin/date.txt"
# create empty file
def create_file():
fmt = "%Y-%m-%d %H:%M:%S.%f"
str1 = datetime.utcnow().strftime(fmt)[:-3]
# Function creates an empty file
# %d - date, %B - month, %Y - Year
with open(FILEDATE, "w") as file:
file.write(str1)
file.close()
def set_version():
filename=FILESUBVERSION
build=0
mode = 'r' if os.path.exists(filename) else 'w+'
with open(filename, encoding="utf8", mode=mode) as file_in:
_str_build = file_in.read()
file_in.close()
try:
build = int(_str_build)
except ValueError as err:
print("Build.__setVers(): при конвертировании строки в число, err=", err)
finally:
pass
build += 1
str_build = str(build)
while len(str_build) < 5:
str_build = "0" + str_build
print("Build.set_version(): new build=", str_build)
with open(filename, "w", encoding="utf8") as file_in:
file_in.write(str_build)
file_in.close()
# Driver Code
create_file()
set_version()

52
cmd/test_copy/VersionToFile.py Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/python3
# Python script to create an empty file
# with current date as name.
# importing datetime module
from datetime import datetime
import os
# datetime.datetime.now() to get
# current date as filename.
# TimeNow = datetime.datetime.now()
FILESUBVERSION="subversion.txt"
FILEDATE="date.txt"
# create empty file
def create_file():
fmt = "%Y-%m-%d %H:%M:%S.%f"
str1 = datetime.utcnow().strftime(fmt)[:-3]
# Function creates an empty file
# %d - date, %B - month, %Y - Year
with open(FILEDATE, "w") as file:
file.write(str1)
file.close()
def set_vers():
filename=FILESUBVERSION
build=0
mode = 'r' if os.path.exists(filename) else 'w+'
with open(filename, encoding="utf8", mode=mode) as file_in:
_str_build = file_in.read()
file_in.close()
try:
build = int(_str_build)
except ValueError as err:
print("Build.__setVers(): при конвертировании строки в число, err=", err)
finally:
pass
build += 1
str_build = str(build)
while len(str_build) < 5:
str_build = "0" + str_build
print("Build.__set_vers(): new build=", str_build)
with open(filename, "w", encoding="utf8") as file_in:
file_in.write(str_build)
file_in.close()
# Driver Code
create_file()
set_vers()

1
cmd/test_copy/date.txt Normal file
View File

@ -0,0 +1 @@
2022-03-14 10:13:39.265

View File

@ -0,0 +1 @@
00001

View File

@ -0,0 +1 @@
v0

54
docs/connections.graphml Normal file
View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.21.1-->
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="144.0" x="20.0" y="0.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="136.015625" x="3.9921875" xml:space="preserve" y="1.6875">image_database</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n1">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="96.0" x="44.0" y="81.22559999999999"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="72.9609375" x="11.51953125" xml:space="preserve" y="1.6875">Postgres</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<edge id="e0" source="n0" target="n1">
<data key="d8" xml:space="preserve"><![CDATA[image_database -> Postgres]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="13.0" tx="0.0" ty="-13.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="standard" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="-15.2578125" xml:space="preserve" y="18.300299999999993">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graph>
<data key="d6">
<y:Resources/>
</data>
</graphml>

BIN
docs/connections.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

597
docs/packages.graphml Normal file
View File

@ -0,0 +1,597 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.21.1-->
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="304.28125" width="1108.306640625" x="-15.0" y="-304.28125"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="7.1787109375" x="550.56396484375" xml:space="preserve" y="-15.640625">.</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="20.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="8.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="20.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0:">
<node id="n0::n0" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="12.0" width="40.0" x="70.0" y="-221.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="19.4638671875" x="10.26806640625" xml:space="preserve" y="-15.640625">bin</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="40.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="18.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="40.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n0:"/>
</node>
<node id="n0::n1" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="12.0" width="40.0" x="0.0" y="-221.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="25.5869140625" x="7.20654296875" xml:space="preserve" y="-15.640625">cmd</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="40.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="18.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="40.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n1:"/>
</node>
<node id="n0::n2" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="258.640625" width="758.0" x="125.0" y="-273.640625"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="130.279296875" x="313.8603515625" xml:space="preserve" y="-15.640625">internal (2 func, 35 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="280.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="138.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="280.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2:">
<node id="n0::n2::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="64.0" x="140.0" y="-56.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="43.9765625" x="10.01171875" xml:space="preserve" y="1.6875">main</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n0::n2::n1" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="110.0" x="244.0" y="-114.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="122.3349609375" x="-6.16748046875" xml:space="preserve" y="-15.640625">config (3 func, 53 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="260.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="128.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="260.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2::n1:">
<node id="n0::n2::n1::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="80.0" x="259.0" y="-99.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="52.9609375" x="13.51953125" xml:space="preserve" y="1.6875">config</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
<node id="n0::n2::n2" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="134.0" x="359.0" y="-200.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="96.4609375" x="18.76953125" xml:space="preserve" y="-15.640625">constants (6 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="200.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="98.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="200.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2::n2:">
<node id="n0::n2::n2::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="104.0" x="374.0" y="-185.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="81.890625" x="11.0546875" xml:space="preserve" y="1.6875">constants</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
<node id="n0::n2::n3" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="102.0" x="498.0" y="-243.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="121.6171875" x="-9.80859375" xml:space="preserve" y="-15.640625">logic (4 func, 127 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="260.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="128.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="260.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2::n3:">
<node id="n0::n2::n3::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="72.0" x="513.0" y="-228.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.6328125" x="15.18359375" xml:space="preserve" y="1.6875">logic</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
<node id="n0::n2::n4" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="126.0" x="620.0" y="-157.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="141.5146484375" x="-7.75732421875" xml:space="preserve" y="-15.640625">postgres (2 func, 229 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="290.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="143.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="290.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2::n4:">
<node id="n0::n2::n4::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="96.0" x="635.0" y="-142.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="73.46875" x="11.265625" xml:space="preserve" y="1.6875">postgres</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
<node id="n0::n2::n5" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="102.0" x="766.0" y="-200.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="81.6904296875" x="10.15478515625" xml:space="preserve" y="-15.640625">types (43 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="170.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="83.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="170.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n2::n5:">
<node id="n0::n2::n5::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="72.0" x="781.0" y="-185.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="48.078125" x="11.9609375" xml:space="preserve" y="1.6875">types</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
</graph>
</node>
<node id="n0::n3" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="101.640625" width="182.61328125" x="895.693359375" y="-230.640625"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="22.486328125" x="80.0634765625" xml:space="preserve" y="-15.640625">pkg</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="40.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="18.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="40.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n3:">
<node id="n0::n3::n0" yfiles.foldertype="group">
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="56.0" width="118.0" x="928.0" y="-200.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#F5F5F5" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" height="15.640625" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="152.61328125" x="-17.306640625" xml:space="preserve" y="-15.640625">graphml (24 func, 1084 lines)</y:NodeLabel>
<y:Shape type="roundrectangle"/>
<y:State closed="false" closedHeight="80.0" closedWidth="100.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="12.0" width="300.0" x="0.0" y="0.0"/>
<y:Fill color="#F5F5F5" transparent="false"/>
<y:BorderStyle color="#000000" type="dashed" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="content" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="10" fontStyle="plain" hasLineColor="false" hasText="false" height="4.0" horizontalTextPosition="center" iconTextGap="4" modelName="sandwich" modelPosition="n" textColor="#000000" verticalTextPosition="bottom" visible="true" width="4.0" x="148.0" y="-4.0"/>
<y:Shape type="roundrectangle"/>
<y:State closed="true" closedHeight="12.0" closedWidth="300.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
<y:BorderInsets bottom="54" bottomF="54.0" left="0" leftF="0.0" right="23" rightF="23.35" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n0::n3::n0:">
<node id="n0::n3::n0::n0">
<data key="d5">
<y:ShapeNode>
<y:Geometry height="26.0" width="88.0" x="943.0" y="-185.0"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="70.8671875" x="8.56640625" xml:space="preserve" y="1.6875">graphml</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
</graph>
</node>
</graph>
</node>
</graph>
</node>
<edge id="n0::n2::e0" source="n0::n2::n0" target="n0::n2::n1::n0">
<data key="d8" xml:space="preserve"><![CDATA[main -> config]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="-3.7142857142857153" tx="0.0" ty="0.0">
<y:Point x="234.0" y="-46.714285714285715"/>
<y:Point x="234.0" y="-86.0"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="14.7431640625" xml:space="preserve" y="-28.955356052943642">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e1" source="n0::n2::n0" target="n0::n2::n2::n0">
<data key="d8" xml:space="preserve"><![CDATA[main -> constants]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="-7.428571428571431" tx="0.0" ty="0.0">
<y:Point x="224.0" y="-50.42857142857143"/>
<y:Point x="224.0" y="-172.0"/>
</y:Path>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="75.162109375" xml:space="preserve" y="-130.88393020629883">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e2" source="n0::n2::n0" target="n0::n2::n3::n0">
<data key="d8" xml:space="preserve"><![CDATA[main -> logic]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="-11.142857142857139" tx="0.0" ty="0.0">
<y:Point x="214.0" y="-54.14285714285714"/>
<y:Point x="214.0" y="-215.0"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="139.646484375" xml:space="preserve" y="-170.1696434020996">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::e0" source="n0::n2::n0" target="n0::n3::n0::n0">
<data key="d8" xml:space="preserve"><![CDATA[main -> graphml]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="10.400000000000006">
<y:Point x="903.0" y="-43.0"/>
<y:Point x="903.0" y="-161.6"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="338.8046875" xml:space="preserve" y="-9.3125">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e3" source="n0::n2::n3::n0" target="n0::n2::n4::n0">
<data key="d8" xml:space="preserve"><![CDATA[logic -> postgres]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="10.400000000000006" tx="0.0" ty="-8.666666666666657">
<y:Point x="610.0" y="-204.6"/>
<y:Point x="610.0" y="-137.66666666666666"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="9.73193359375" xml:space="preserve" y="24.1541727701823">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e4" source="n0::n2::n3::n0" target="n0::n2::n5::n0">
<data key="d8" xml:space="preserve"><![CDATA[logic -> types]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="5.199999999999989" tx="0.0" ty="0.0">
<y:Point x="625.0" y="-209.8"/>
<y:Point x="625.0" y="-172.0"/>
</y:Path>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="98.146484375" xml:space="preserve" y="28.487503051757812">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::e1" source="n0::n2::n3::n0" target="n0::n3::n0::n0">
<data key="d8" xml:space="preserve"><![CDATA[logic -> graphml]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="-5.199999999999989">
<y:Point x="893.0" y="-215.0"/>
<y:Point x="893.0" y="-177.2"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="143.3046875" xml:space="preserve" y="-9.3125">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e5" source="n0::n2::n4::n0" target="n0::n2::n1::n0">
<data key="d8" xml:space="preserve"><![CDATA[postgres -> config]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="-8.666666666666671">
<y:Point x="364.0" y="-129.0"/>
<y:Point x="364.0" y="-94.66666666666667"/>
</y:Path>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="-155.3203125" xml:space="preserve" y="-9.3125">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::n2::e6" source="n0::n2::n4::n0" target="n0::n2::n5::n0">
<data key="d8" xml:space="preserve"><![CDATA[postgres -> types]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="8.666666666666657">
<y:Point x="756.0" y="-129.0"/>
<y:Point x="756.0" y="-163.33333333333334"/>
</y:Path>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="9.7421875" xml:space="preserve" y="-26.479166666666686">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::e2" source="n0::n3::n0::n0" target="n0::n2::n5::n0">
<data key="d8" xml:space="preserve"><![CDATA[graphml -> types]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="-60.2578125" xml:space="preserve" y="-9.3125">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="n0::e3" source="n0::n3::n0::n0" target="n0::n2::n1::n0">
<data key="d8" xml:space="preserve"><![CDATA[graphml -> config]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="5.199999999999989" tx="0.0" ty="0.0">
<y:Point x="893.0" y="-166.8"/>
<y:Point x="893.0" y="-86.0"/>
</y:Path>
<y:LineStyle color="#000000" type="dashed" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" bottomInset="0" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.625" horizontalTextPosition="center" iconTextGap="4" leftInset="0" modelName="centered" modelPosition="center" preferredPlacement="anywhere" ratio="0.5" rightInset="0" textColor="#000000" topInset="0" verticalTextPosition="bottom" visible="true" width="30.515625" x="-337.6787109375" xml:space="preserve" y="71.48750305175781">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graph>
<data key="d6">
<y:Resources/>
</data>
</graphml>

BIN
docs/packages.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -0,0 +1,259 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.21.1-->
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="212.0" width="254.7" x="-269.85" y="378.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="46.7265625" x="103.98671875" xml:space="preserve" y="4.0">timer</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="190.25" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="234.9375" x="2.0" xml:space="preserve" y="30.0">due_date_ int8
element_instance_key_ int8
key_ int8
process_definition_key_ int8
process_instance_key_ int8
repetitions int4
state_ varchar
target_element_id_ varchar
timestamp_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n1">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="250.0" width="254.7" x="-269.85" y="1352.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="145.7578125" x="54.471093749999994" xml:space="preserve" y="4.0">element_instance</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="227.5" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="247.1015625" x="2.0" xml:space="preserve" y="30.0">bpmn_element_type_ varchar
element_id_ varchar
flow_scope_key_ int8
id varchar
intent_ varchar
key_ int8
partition_id_ int4
position_ int8
process_definition_key_ int8
process_instance_key_ int8
timestamp_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n2">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="155.0" width="239.4" x="-269.7" y="-1068.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="43.3671875" x="98.01640624999999" xml:space="preserve" y="4.0">error</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="134.375" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="227.40625" x="2.0" xml:space="preserve" y="30.0">error_event_position_ int8
exception_message_ oid
position_ int8
process_instance_key_ int8
stacktrace_ oid
timestamp_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n3">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="79.0" width="154.9" x="-269.95" y="-1483.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="136.8046875" x="9.047656249999989" xml:space="preserve" y="4.0">hazelcast_config</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="59.875" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="122.3125" x="2.0" xml:space="preserve" y="30.0">id varchar
sequence int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n4">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="174.0" width="224.0" x="-270.0" y="-813.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="75.90625" x="74.046875" xml:space="preserve" y="4.0">message</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="153.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="206.40625" x="2.0" xml:space="preserve" y="30.0">correlation_key_ varchar
key_ int8
message_id_ varchar
name_ varchar
payload_ oid
state_ varchar
timestamp_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n5">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="136.0" width="224.0" x="-270.0" y="-1304.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="65.8359375" x="79.08203125" xml:space="preserve" y="4.0">process</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="115.75" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="221.8203125" x="2.0" xml:space="preserve" y="30.0">bpmn_process_id_ varchar
key_ int8
resource_ oid
timestamp_ int8
version_ int4
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n6">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="231.0" width="293.1" x="-269.55" y="1021.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="141.6171875" x="75.74140625000001" xml:space="preserve" y="4.0">process_instance</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="208.875" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="292.34375" x="2.0" xml:space="preserve" y="30.0">bpmn_process_id_ varchar
end_ int8
key_ int8
parent_element_instance_key_ int8
parent_process_instance_key_ int8
partition_id_ int4
process_definition_key_ int8
start_ int8
state_ varchar
version_ int4
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n7">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="231.0" width="254.7" x="-269.85" y="690.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="68.2421875" x="93.22890625" xml:space="preserve" y="4.0">incident</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="208.875" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="234.9375" x="2.0" xml:space="preserve" y="30.0">bpmn_process_id_ varchar
created_ int8
element_instance_key_ int8
error_msg_ oid
error_type_ varchar
job_key_ int8
key_ int8
process_definition_key_ int8
process_instance_key_ int8
resolved_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n8">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="193.0" width="239.4" x="-269.7" y="-539.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="28.390625" x="105.50468749999999" xml:space="preserve" y="4.0">job</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="171.625" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="231.546875" x="2.0" xml:space="preserve" y="30.0">element_instance_key_ int8
job_type_ varchar
key_ int8
process_instance_key_ int8
retries_ int4
state_ varchar
timestamp_ int8
worker_ varchar
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n9">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="212.0" width="254.7" x="-269.85" y="66.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="181.5" x="36.599999999999994" xml:space="preserve" y="4.0">message_subscription</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="190.25" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="243.7578125" x="2.0" xml:space="preserve" y="30.0">correlation_key_ varchar
element_instance_key_ int8
id_ varchar
message_name_ varchar
process_definition_key_ int8
process_instance_key_ int8
state_ varchar
target_flow_node_id_ varchar
timestamp_ int8
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n10">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="212.0" width="239.4" x="-269.7" y="-246.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="22.625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="68.546875" x="85.42656249999999" xml:space="preserve" y="4.0">variable</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="190.25" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="227.40625" x="2.0" xml:space="preserve" y="30.0">id varchar
name_ varchar
partition_id_ int4
position_ int8
process_instance_key_ int8
scope_key_ int8
state_ varchar
timestamp_ int8
value_ oid
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
</graph>
<data key="d6">
<y:Resources/>
</data>
</graphml>

View File

@ -0,0 +1,292 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="326.0" width="216.3" x="671.849976" y="-343.000000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="326.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="216.3" x="16.0" xml:space="preserve" y="4.0">contract_black_items</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="326.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="216.3" x="2.0" xml:space="preserve" y="30.0">id int8
contract_id int8
contract_number text
created_at timestamptz
created_by_id int8
date_from timestamptz
date_to timestamptz
deleted_at timestamptz
edms_link text
ext_id int8
is_deleted bool
modified_at timestamptz
modified_by_id int8
note text
reason text
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n1">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="269.0" width="216.3" x="-318.149994" y="105.500000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="269.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="216.3" x="16.0" xml:space="preserve" y="4.0">contract_category_types</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="269.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="216.3" x="2.0" xml:space="preserve" y="30.0">id int8
code text
connection_id int8
created_at timestamptz
deleted_at timestamptz
description text
ext_id int8
is_deleted bool
is_group bool
modified_at timestamptz
name text
parent_id int8
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n2">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="79.0" width="185.6" x="-302.799988" y="-3.500000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="79.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="185.6" x="16.0" xml:space="preserve" y="4.0">contract_individuals</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="79.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="185.6" x="2.0" xml:space="preserve" y="30.0">contract_id int8
individual_id int8
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n3">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="79.0" width="201.0" x="281.899994" y="-309.500000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="79.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="201.0" x="16.0" xml:space="preserve" y="4.0">contract_organizations</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="79.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="201.0" x="2.0" xml:space="preserve" y="30.0">contract_id int8
organization_id int8
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n4">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="326.0" width="216.3" x="671.849976" y="17.000000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="326.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="216.3" x="16.0" xml:space="preserve" y="4.0">contract_white_items</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="326.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="216.3" x="2.0" xml:space="preserve" y="30.0">id int8
contract_id int8
contract_number text
created_at timestamptz
created_by_id int8
date_from timestamptz
date_to timestamptz
deleted_at timestamptz
edms_link text
ext_id int8
is_deleted bool
modified_at timestamptz
modified_by_id int8
note text
reason text
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n5">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="706.0" width="277.8" x="205.100006" y="24.000000"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="706.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="277.8" x="16.0" xml:space="preserve" y="4.0">contracts</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="706.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="277.8" x="2.0" xml:space="preserve" y="30.0">id int8
begin_at timestamptz
branch_id int8
category_id int8
connection_id int8
created_at timestamptz
curator_claim_id int8
curator_contract_id int8
curator_legal_id int8
curator_payment_id int8
curator_tech_audit_id int8
days_to_resolve_claim int4
deleted_at timestamptz
description text
email text
end_at timestamptz
error_from_stack_at timestamptz
ext_id int8
individual_id int8
is_deleted bool
is_error_from_stack bool
is_group bool
is_ind_organization bool
is_organization bool
is_valid_email bool
modified_at timestamptz
number text
organization_consignee_id int8
organization_customer_id int8
organization_payer_id int8
parent_id int8
post_address text
sign_at timestamptz
status text
terminate_at timestamptz
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
</graph>
<edge id="e11" source="n4" target="n5">
<data key="d8" xml:space="preserve"><![CDATA[contract_id - id]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-108.16" sy="-104.35" tx="138.88" ty="-313.00"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e12" source="n5" target="n1">
<data key="d8" xml:space="preserve"><![CDATA[category_id - id]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-138.88" sy="-257.04" tx="108.16" ty="-94.50"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e13" source="n0" target="n5">
<data key="d8" xml:space="preserve"><![CDATA[contract_id - id]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-108.16" sy="-104.35" tx="138.88" ty="-313.00"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e14" source="n2" target="n5">
<data key="d8" xml:space="preserve"><![CDATA[contract_id - id]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="92.80" sy="0.50" tx="-138.88" ty="-313.00"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e15" source="n3" target="n5">
<data key="d8" xml:space="preserve"><![CDATA[contract_id - id]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-100.48" sy="0.50" tx="138.88" ty="-313.00"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graphml>

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

23
go.mod Normal file
View File

@ -0,0 +1,23 @@
module github.com/ManyakRus/crud_generator
go 1.20
require (
github.com/ManyakRus/starter v0.0.0-20230913104819-4ee2118a3638
github.com/beevik/etree v1.2.0
gorm.io/gorm v1.25.4
)
require (
github.com/ManyakRus/logrus v0.0.0-20230913114322-14246ee4c48b // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.4.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
gorm.io/driver/postgres v1.5.2 // indirect
)

42
go.sum Normal file
View File

@ -0,0 +1,42 @@
github.com/ManyakRus/logrus v0.0.0-20230913114322-14246ee4c48b h1:U17+MOkhFzy9WkjANQhe1JftWq8Opt4gmy2G59wreG8=
github.com/ManyakRus/logrus v0.0.0-20230913114322-14246ee4c48b/go.mod h1:OUyxCVbPW/2lC1e6cM7Am941SJiC88BhNnb24x2R3a8=
github.com/ManyakRus/starter v0.0.0-20230913104819-4ee2118a3638 h1:USOEGx2aGUtq5vJlbr5OhLIRTX252cpv5aYre/QNztg=
github.com/ManyakRus/starter v0.0.0-20230913104819-4ee2118a3638/go.mod h1:wRsJrHV9PcbL8NSxOR14dnWUQ9MSraiZHw1uMQb/ojQ=
github.com/beevik/etree v1.2.0 h1:l7WETslUG/T+xOPs47dtd6jov2Ii/8/OjCldk5fYfQw=
github.com/beevik/etree v1.2.0/go.mod h1:aiPf89g/1k3AShMVAzriilpcE4R/Vuor90y83zVZWFc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=
github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
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=
gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0=
gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8=
gorm.io/gorm v1.25.4 h1:iyNd8fNAe8W9dvtlgeRI5zSVZPsq3OpcTu37cYcpCmw=
gorm.io/gorm v1.25.4/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=

53
internal/config/config.go Normal file
View File

@ -0,0 +1,53 @@
package config
import (
"os"
)
const FILENAME_GRAPHML = "connections.graphml"
// Settings хранит все нужные переменные окружения
var Settings SettingsINI
// SettingsINI - структура для хранения всех нужных переменных окружения
type SettingsINI struct {
FILENAME_GRAPHML string
INCLUDE_TABLES string
EXCLUDE_TABLES string
}
// FillSettings загружает переменные окружения в структуру из переменных окружения
func FillSettings() {
Settings = SettingsINI{}
Settings.FILENAME_GRAPHML = os.Getenv("FILENAME_GRAPHML")
Settings.INCLUDE_TABLES = os.Getenv("INCLUDE_TABLES")
Settings.EXCLUDE_TABLES = os.Getenv("EXCLUDE_TABLES")
if Settings.FILENAME_GRAPHML == "" {
Settings.FILENAME_GRAPHML = FILENAME_GRAPHML
}
//
}
// CurrentDirectory - возвращает текущую директорию ОС
func CurrentDirectory() string {
Otvet, err := os.Getwd()
if err != nil {
//log.Println(err)
}
return Otvet
}
// FillFlags - заполняет параметры из командной строки
func FillFlags() {
Args := os.Args[1:]
if len(Args) > 1 {
return
}
if len(Args) > 0 {
Settings.FILENAME_GRAPHML = Args[0]
}
}

View File

@ -0,0 +1 @@
package config

View File

@ -0,0 +1,6 @@
package constants
const TEXT_HELP = `
Run the image_connections file with parameters:
image_connections <your repository directory> <filename.graphml>
`

127
internal/logic/logic.go Normal file
View File

@ -0,0 +1,127 @@
package logic
import (
"github.com/ManyakRus/crud_generator/internal/postgres"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/crud_generator/pkg/graphml"
"github.com/ManyakRus/starter/log"
"sort"
)
//var MassTable []types.Table
func StartFillAll(FileName string) bool {
Otvet := false
//заполним MapAll
MapAll, err := postgres.FillMapTable()
if err != nil {
log.Error("FillMapTable() error: ", err)
return Otvet
}
if len(MapAll) > 0 {
Otvet = true
}
if Otvet == false {
println("warning: Empty file not saved !")
return Otvet
}
//создадим документ
DocXML, ElementInfoGraph := graphml.CreateDocument()
//заполним прямоугольники в документ
err = FillEntities(ElementInfoGraph, &MapAll)
if err != nil {
log.Error("FillEntities() error: ", err)
return Otvet
}
//заполним стрелки в документ
err = FillEdges(ElementInfoGraph, &MapAll)
if err != nil {
log.Error("FillEdges() error: ", err)
return Otvet
}
log.Info("Start save file")
DocXML.Indent(2)
err = DocXML.WriteToFile(FileName)
if err != nil {
log.Error("WriteToFile() FileName: ", FileName, " error: ", err)
}
return Otvet
}
// FillEntities - заполняет прямоугольники Entities в файл .xml
func FillEntities(ElementInfoGraph types.ElementInfoStruct, MapAll *map[string]*types.Table) error {
var err error
for _, table1 := range *MapAll {
TextAttributes := ""
MassColumns := MassFromMapColumns(table1.MapColumns)
for _, column1 := range MassColumns {
if TextAttributes != "" {
TextAttributes = TextAttributes + "\n"
}
TextAttributes = TextAttributes + column1.Name + " " + column1.Type
}
ElementInfo1 := graphml.CreateElement_Entity(ElementInfoGraph, table1.Name, TextAttributes)
table1.ElementInfo = ElementInfo1
}
return err
}
// MassFromMapColumns - возвращает Slice из Map
func MassFromMapColumns(MapColumns map[string]types.Column) []types.Column {
Otvet := make([]types.Column, 0)
for _, v := range MapColumns {
Otvet = append(Otvet, v)
}
sort.Slice(Otvet[:], func(i, j int) bool {
return Otvet[i].OrderNumber < Otvet[j].OrderNumber
})
return Otvet
}
// FillEdges - заполняет стрелки в файл .xml
func FillEdges(ElementInfoGraph types.ElementInfoStruct, MapAll *map[string]*types.Table) error {
var err error
MapAll0 := *MapAll
for _, table1 := range *MapAll {
for _, column1 := range table1.MapColumns {
if column1.TableKey == "" || column1.ColumnKey == "" {
continue
}
//только если есть внешний ключ
//тыблица из ключа
TableKey, ok := MapAll0[column1.TableKey]
if ok == false {
log.Warn("Error. Not found table name: ", column1.TableKey)
continue
}
//колонка из ключа
ColumnKey, ok := TableKey.MapColumns[column1.ColumnKey]
if ok == false {
log.Warn("Error. Not found column name: ", column1.ColumnKey)
continue
}
//
decription := column1.Name + " - " + ColumnKey.Name
graphml.CreateElement_Edge(ElementInfoGraph, table1.ElementInfo, TableKey.ElementInfo, "", decription, column1.OrderNumber+1, ColumnKey.OrderNumber+1)
}
}
return err
}

View File

@ -0,0 +1,27 @@
package logic
import (
"github.com/ManyakRus/crud_generator/internal/config"
ConfigMain "github.com/ManyakRus/starter/config"
"github.com/ManyakRus/starter/micro"
"testing"
)
func TestStartFillAll(t *testing.T) {
ConfigMain.LoadEnv()
config.FillSettings()
dir := micro.ProgramDir()
FileName := dir + "test" + micro.SeparatorFile() + "test_start.xgml"
StartFillAll(FileName)
}
func TestFindRepositoryName(t *testing.T) {
ConfigMain.LoadEnv()
config.FillSettings()
Otvet := FindRepositoryName()
if Otvet == "" {
t.Error("TestFindRepositoryName() error: =''")
}
}

35
internal/main.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/constants"
"github.com/ManyakRus/crud_generator/internal/logic"
"github.com/ManyakRus/crud_generator/pkg/graphml"
ConfigMain "github.com/ManyakRus/starter/config"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/postgres_gorm"
)
func main() {
StartApp()
}
func StartApp() {
ConfigMain.LoadEnv()
config.FillSettings()
config.FillFlags()
postgres_gorm.StartDB()
postgres_gorm.GetConnection().Logger.LogMode(1)
graphml.StartReadFile()
FileName := config.Settings.FILENAME_GRAPHML
log.Info("file graphml: ", FileName)
log.Info("postgres host: ", postgres_gorm.Settings.DB_HOST)
ok := logic.StartFillAll(FileName)
if ok == false {
println(constants.TEXT_HELP)
}
}

9
internal/main_test.go Normal file
View File

@ -0,0 +1,9 @@
package main
import (
"testing"
)
func TestStartApp(t *testing.T) {
StartApp()
}

View File

@ -0,0 +1,229 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/postgres_gorm"
"gorm.io/gorm"
"strings"
"time"
)
type TableColumn struct {
TableName string `json:"table_name" gorm:"column:table_name;default:''"`
ColumnName string `json:"column_name" gorm:"column:column_name;default:''"`
ColumnType string `json:"type_name" gorm:"column:type_name;default:''"`
ColumnIsIdentity string `json:"is_identity" gorm:"column:is_identity;default:''"`
ColumnDescription string `json:"description" gorm:"column:description;default:''"`
ColumnTableKey string `json:"table_key" gorm:"column:table_key;default:''"`
ColumnColumnKey string `json:"column_key" gorm:"column:column_key;default:''"`
}
// FillMapTable - возвращает массив MassTable данными из БД
func FillMapTable() (map[string]*types.Table, error) {
var err error
//MassTable := make([]types.Table, 0)
MapTable := make(map[string]*types.Table, 0)
TextSQL := `
drop table if exists temp_keys;
CREATE TEMPORARY TABLE temp_keys (table_from text, column_from text, table_to text, column_to text);
------------------------------------------- Все внешние ключи ------------------------------
insert into temp_keys
SELECT
(select r.relname from pg_class r where r.oid = c.conrelid) as table_from,
UNNEST((select array_agg(attname) from pg_attribute where attrelid = c.conrelid and array[attnum] <@ c.conkey)) as column_from,
(select r.relname from pg_class r where r.oid = c.confrelid) as table_to,
a.attname as column_to
FROM
pg_constraint c
join
pg_attribute a
on
c.confrelid=a.attrelid and a.attnum = ANY(confkey)
WHERE 1=1
--and c.confrelid = (select oid from pg_class where relname = 'debt_types')
AND c.confrelid!=c.conrelid
;
------------------------------------------- Все таблицы и колонки ------------------------------
SELECT
c.table_name,
c.column_name,
c.udt_name as type_name,
c.is_identity as is_identity,
COALESCE(pgd.description, '') as description,
COALESCE(keys.table_to, '') as table_key,
COALESCE(keys.column_to, '') as column_key
FROM
pg_catalog.pg_statio_all_tables as st
inner join
pg_catalog.pg_description pgd
on
pgd.objoid = st.relid
right join
information_schema.columns c
on
pgd.objsubid = c.ordinal_position
and c.table_schema = st.schemaname
and c.table_name = st.relname
LEFT JOIN --внешние ключи
temp_keys as keys
ON
keys.table_from = c.table_name
and keys.column_from = c.column_name
LEFT JOIN --вьюхи
INFORMATION_SCHEMA.views as v
ON
v.table_schema = 'public'
and v.table_name = c.table_name
where 1=1
and c.table_schema='public'
and v.table_name is null
--INCLUDE_TABLES
--EXCLUDE_TABLES
order by
table_name,
is_identity desc,
column_name
`
SCHEMA := strings.Trim(postgres_gorm.Settings.DB_SCHEMA, " ")
if SCHEMA != "" {
TextSQL = strings.ReplaceAll(TextSQL, "public", SCHEMA)
}
if config.Settings.INCLUDE_TABLES != "" {
TextSQL = strings.ReplaceAll(TextSQL, "--INCLUDE_TABLES", "and c.table_name ~* '"+config.Settings.INCLUDE_TABLES+"'")
}
if config.Settings.EXCLUDE_TABLES != "" {
TextSQL = strings.ReplaceAll(TextSQL, "--EXCLUDE_TABLES", "and c.table_name !~* '"+config.Settings.EXCLUDE_TABLES+"'")
}
//соединение
ctxMain := contextmain.GetContext()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*60)
defer ctxCancelFunc()
db := postgres_gorm.GetConnection()
db.WithContext(ctx)
//запрос
//запустим все запросы отдельно
var tx *gorm.DB
sqlSlice := strings.Split(TextSQL, ";")
len1 := len(sqlSlice)
for i, TextSQL1 := range sqlSlice {
//batch.Queue(TextSQL1)
if i == len1-1 {
tx = db.Raw(TextSQL1)
} else {
tx = db.Exec(TextSQL1)
//rows.Close()
}
err = tx.Error
if err != nil {
log.Panic("DB.Raw() error:", err)
}
}
//tx := db.Raw(TextSQL)
//err = tx.Error
//if err != nil {
// sError := fmt.Sprint("db.Raw() error: ", err)
// log.Panicln(sError)
// return MassTable, err
//}
//ответ в структуру
MassTableColumn := make([]TableColumn, 0)
tx = tx.Scan(&MassTableColumn)
err = tx.Error
if err != nil {
sError := fmt.Sprint("Get_error() error: ", err)
log.Panicln(sError)
return MapTable, err
}
//проверка 0 строк
if tx.RowsAffected == 0 {
sError := fmt.Sprint("db.Raw() RowsAffected =0 ")
log.Warn(sError)
err = errors.New(sError)
//log.Panicln(sError)
return MapTable, err
}
//заполним MapTable
MapColumns := make(map[string]types.Column, 0)
OrderNumberColumn := 0
OrderNumberTable := 0
TableName0 := ""
Table1 := CreateTable()
for _, v := range MassTableColumn {
if v.TableName != TableName0 {
OrderNumberColumn = 0
Table1.MapColumns = MapColumns
MapColumns = make(map[string]types.Column, 0)
if TableName0 != "" {
//MassTable = append(MassTable, Table1)
MapTable[TableName0] = Table1
OrderNumberTable++
}
Table1 = CreateTable()
Table1.Name = v.TableName
Table1.OrderNumber = OrderNumberTable
}
Column1 := types.Column{}
Column1.Name = v.ColumnName
Column1.Type = v.ColumnType
if v.ColumnIsIdentity == "YES" {
Column1.Is_identity = true
}
Column1.Description = v.ColumnDescription
Column1.OrderNumber = OrderNumberColumn
Column1.TableKey = v.ColumnTableKey
Column1.ColumnKey = v.ColumnColumnKey
MapColumns[v.ColumnName] = Column1
//Table1.Columns = append(Table1.Columns, Column1)
OrderNumberColumn++
TableName0 = v.TableName
}
if Table1.Name != "" {
Table1.MapColumns = MapColumns
MapTable[TableName0] = Table1
}
return MapTable, err
}
func CreateTable() *types.Table {
Otvet := &types.Table{}
Otvet.MapColumns = make(map[string]types.Column, 0)
return Otvet
}

View File

@ -0,0 +1,22 @@
package postgres
import (
ConfigMain "github.com/ManyakRus/starter/config"
"github.com/ManyakRus/starter/postgres_gorm"
"testing"
)
func TestFillMassTable(t *testing.T) {
ConfigMain.LoadEnv()
postgres_gorm.Connect()
defer postgres_gorm.CloseConnection()
Otvet, err := FillMapTable()
if err != nil {
t.Error("TestFillMassTable() error: ", err)
}
if len(Otvet) == 0 {
t.Error("TestFillMassTable() error: len =0")
}
}

43
internal/types/types.go Normal file
View File

@ -0,0 +1,43 @@
package types
import (
"github.com/beevik/etree"
)
type Column struct {
Name string `json:"name" gorm:"column:name;default:''"`
Type string `json:"type_name" gorm:"column:type_name;default:''"`
Is_identity bool `json:"is_identity" gorm:"column:is_identity;default:false"`
Description string `json:"description" gorm:"column:description;default:''"`
OrderNumber int
TableKey string `json:"table_key" gorm:"column:table_key;default:''"`
ColumnKey string `json:"column_key" gorm:"column:column_key;default:''"`
}
type Table struct {
Name string `json:"name" gorm:"column:name;default:''"`
//Element *etree.Element
ElementInfo ElementInfoStruct
MapColumns map[string]Column
//Columns []Column
OrderNumber int
}
type NodeStruct struct {
Element *etree.Element
Name string
X float64
Y float64
}
type ElementInfoStruct struct {
Element *etree.Element
Name string
Attribute string
Description string
Width float64
Height float64
Parent *ElementInfoStruct
}
var MapNodeStructOld = make(map[string]NodeStruct, 0)

944
pkg/graphml/graphml.go Normal file
View File

@ -0,0 +1,944 @@
package graphml
import (
"fmt"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/beevik/etree"
_ "github.com/beevik/etree"
"math"
"strconv"
"strings"
)
// FONT_SIZE_ENTITY - размер шрифта Entity
var FONT_SIZE_ENTITY = 16
// FONT_SIZE_BENDS - размер шрифта стрелки куриная лапка
var FONT_SIZE_BENDS = 8
// FONT_SIZE_SHAPE - размер шрифта прямоугольника
var FONT_SIZE_SHAPE = 16
// FONT_SIZE_SHAPE - размер шрифта групп
var FONT_SIZE_GROUP = 10
// FONT_SIZE_EDGE - размер шрифта стрелок
var FONT_SIZE_EDGE = 8
// CreateElement_Entity - создаёт элемент - Entity
func CreateElement_Entity(ElementInfoMain types.ElementInfoStruct, ElementName, ElementAttribute string) types.ElementInfoStruct {
Width := findWidth_Entity(ElementName + "\n" + ElementAttribute)
Height := findHeight_Entity(ElementName + ElementAttribute)
sWidth := fmt.Sprintf("%.1f", float64(Width))
sHeight := fmt.Sprintf("%.1f", float64(Height))
sFontSize := strconv.Itoa(FONT_SIZE_ENTITY)
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoMain.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoMain.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoNode types.ElementInfoStruct
ElementInfoNode.Element = ElementNode
ElementInfoNode.Name = ElementName
ElementInfoNode.Parent = &ElementInfoMain
ElementInfoNode.Attribute = ElementAttribute
ElementInfoNode.Width = Width
ElementInfoNode.Height = Height
sId := FindId(ElementInfoMain, ElementInfoNode)
ElementNode.CreateAttr("id", sId)
//ElementNode.CreateAttr("id", "n"+strconv.Itoa(ElementNode.Index()))
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d4")
//data
ElementData2 := ElementNode.CreateElement("data")
ElementData2.CreateAttr("key", "d5")
//y:GenericNode
ElementYGenericNode := ElementData2.CreateElement("y:GenericNode")
ElementYGenericNode.CreateAttr("configuration", "com.yworks.entityRelationship.big_entity")
sx := "-270"
sy := "-65"
NodeStructOld, ok := types.MapNodeStructOld[ElementName]
if ok == true {
sx = fmt.Sprintf("%f", NodeStructOld.X)
sy = fmt.Sprintf("%f", NodeStructOld.Y)
}
//YGeometry
ElementYGeometry := ElementYGenericNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", sx)
ElementYGeometry.CreateAttr("y", sy)
//YFill
ElementYFill := ElementYGenericNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//BorderStyle
ElementBorderStyle := ElementYGenericNode.CreateElement("y:BorderStyle")
ElementBorderStyle.CreateAttr("color", "#000000")
ElementBorderStyle.CreateAttr("type", "line")
ElementBorderStyle.CreateAttr("width", "1.0")
//NodeLabel
ElementNodeLabel := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel.CreateAttr("alignment", "center")
ElementNodeLabel.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel.CreateAttr("backgroundColor", "#B7C9E3")
ElementNodeLabel.CreateAttr("configuration", "com.yworks.entityRelationship.label.name")
ElementNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel.CreateAttr("fontSize", sFontSize)
ElementNodeLabel.CreateAttr("fontStyle", "plain")
ElementNodeLabel.CreateAttr("hasLineColor", "false")
ElementNodeLabel.CreateAttr("height", sHeight)
ElementNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel.CreateAttr("iconTextGap", "4")
ElementNodeLabel.CreateAttr("modelName", "internal")
ElementNodeLabel.CreateAttr("modelPosition", "t")
ElementNodeLabel.CreateAttr("textColor", "#000000")
ElementNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementNodeLabel.CreateAttr("visible", "true")
ElementNodeLabel.CreateAttr("width", sWidth)
ElementNodeLabel.CreateAttr("x", "16.0")
ElementNodeLabel.CreateAttr("xml:space", "preserve")
ElementNodeLabel.CreateAttr("y", "4.0")
ElementNodeLabel.CreateText(ElementName)
//NodeLabel
ElementNodeLabel2 := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel2.CreateAttr("alignment", "left")
ElementNodeLabel2.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel2.CreateAttr("configuration", "com.yworks.entityRelationship.label.attributes")
ElementNodeLabel2.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel2.CreateAttr("fontSize", sFontSize)
ElementNodeLabel2.CreateAttr("fontStyle", "plain")
ElementNodeLabel2.CreateAttr("hasBackgroundColor", "false")
ElementNodeLabel2.CreateAttr("hasLineColor", "false")
ElementNodeLabel2.CreateAttr("height", sHeight)
ElementNodeLabel2.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel2.CreateAttr("iconTextGap", "4")
ElementNodeLabel2.CreateAttr("modelName", "free")
ElementNodeLabel2.CreateAttr("modelPosition", "anywhere")
ElementNodeLabel2.CreateAttr("textColor", "#000000")
ElementNodeLabel2.CreateAttr("verticalTextPosition", "top")
ElementNodeLabel2.CreateAttr("visible", "true")
ElementNodeLabel2.CreateAttr("width", sWidth)
ElementNodeLabel2.CreateAttr("x", "2.0")
ElementNodeLabel2.CreateAttr("xml:space", "preserve")
ElementNodeLabel2.CreateAttr("y", "30.0")
ElementNodeLabel2.CreateText(ElementAttribute)
//y:LabelModel
ElementYLabelModel := ElementNodeLabel2.CreateElement("y:LabelModel")
//y:ErdAttributesNodeLabelModel
ElementYLabelModel.CreateElement("y:ErdAttributesNodeLabelModel")
//y:ModelParameter
ElementYModelParameter := ElementNodeLabel2.CreateElement("y:ModelParameter")
//y:ErdAttributesNodeLabelModelParameter
ElementYModelParameter.CreateElement("y:ErdAttributesNodeLabelModelParameter")
//y:StyleProperties
ElementYStyleProperties := ElementYGenericNode.CreateElement("y:StyleProperties")
//y:Property
ElementYProperty := ElementYStyleProperties.CreateElement("y:Property")
ElementYProperty.CreateAttr("class", "java.lang.Boolean")
ElementYProperty.CreateAttr("name", "y.view.ShadowNodePainter.SHADOW_PAINTING")
ElementYProperty.CreateAttr("value", "true")
return ElementInfoNode
}
// CreateElement_Edge - создаёт элемент graphml - стрелка
func CreateElement_Edge(ElementInfoGraph, ElementInfoFrom, ElementInfoTo types.ElementInfoStruct, label, Description string, NumberAttributeFrom, NumberAttributeTo int) types.ElementInfoStruct {
NameFrom := ElementInfoFrom.Name
NodeStructFrom, ok_from := types.MapNodeStructOld[NameFrom]
NameTo := ElementInfoTo.Name
NodeStructTo, ok_to := types.MapNodeStructOld[NameTo]
var sx_koef float32 = 1
var tx_koef float32 = 1
if ok_to == true && ok_from == true {
if NodeStructFrom.X < NodeStructTo.X {
sx_koef = -1
} else {
tx_koef = -1
}
}
//
sx := float32(-ElementInfoFrom.Width/2) * sx_koef
sy := float32(-ElementInfoFrom.Height/2) + 40 + float32(FONT_SIZE_ENTITY)*1.1659*float32(NumberAttributeFrom-1)
tx := float32(-ElementInfoTo.Width/2) * tx_koef
ty := float32(-ElementInfoTo.Height/2) + 40 + float32(FONT_SIZE_ENTITY)*1.1659*float32(NumberAttributeTo-1)
TextSx := fmt.Sprintf("%.2f", sx)
TextSy := fmt.Sprintf("%.2f", sy)
TextTx := fmt.Sprintf("%.2f", tx)
TextTy := fmt.Sprintf("%.2f", ty)
//node
ElementEdge := ElementInfoGraph.Element.CreateElement("edge")
var ElementInfoEdge types.ElementInfoStruct
ElementInfoEdge.Element = ElementEdge
ElementInfoEdge.Parent = &ElementInfoGraph
ElementInfoEdge.Name = label
ElementInfoEdge.Description = Description
//EdgeId := FindId(ElementInfoGraph, ElementEdge)
//EdgeID := EdgeId
EdgeID := "e" + strconv.Itoa(ElementEdge.Index())
ElementEdge.CreateAttr("id", EdgeID)
//Source := "n" + strconv.Itoa(IndexElementFrom) + "::" + "n" + strconv.Itoa(IndexElementTo)
IdFrom := FindId(ElementInfoGraph, ElementInfoFrom)
IdTo := FindId(ElementInfoGraph, ElementInfoTo)
ElementEdge.CreateAttr("source", IdFrom)
ElementEdge.CreateAttr("target", IdTo)
//data
ElementData := ElementEdge.CreateElement("data")
ElementData.CreateAttr("key", "d8")
ElementData.CreateAttr("xml:space", "preserve")
//ElementInfoStruct.CreateText("<![CDATA[descr]]>")
//ElementInfoStruct.CreateElement("![CDATA[descr]]")
ElementData.CreateCData(Description)
//data2
ElementData2 := ElementEdge.CreateElement("data")
ElementData2.CreateAttr("key", "d9")
//y:PolyLineEdge
ElementYPolyLineEdge := ElementData2.CreateElement("y:PolyLineEdge")
//y:Path
ElementYPath := ElementYPolyLineEdge.CreateElement("y:Path")
ElementYPath.CreateAttr("sx", TextSx)
ElementYPath.CreateAttr("sy", TextSy)
ElementYPath.CreateAttr("tx", TextTx)
ElementYPath.CreateAttr("ty", TextTy)
//y:LineStyle
ElementYLineStyle := ElementYPolyLineEdge.CreateElement("y:LineStyle")
ElementYLineStyle.CreateAttr("color", "#000000")
ElementYLineStyle.CreateAttr("type", "line")
ElementYLineStyle.CreateAttr("width", "1.0")
//y:Arrows
ElementYArrows := ElementYPolyLineEdge.CreateElement("y:Arrows")
ElementYArrows.CreateAttr("source", "crows_foot_many")
ElementYArrows.CreateAttr("target", "none")
//y:EdgeLabel
ElementYEdgeLabel := ElementYPolyLineEdge.CreateElement("y:EdgeLabel")
ElementYEdgeLabel.CreateAttr("alignment", "center")
ElementYEdgeLabel.CreateAttr("configuration", "AutoFlippingLabel")
ElementYEdgeLabel.CreateAttr("distance", "0.0")
ElementYEdgeLabel.CreateAttr("fontFamily", "Dialog")
ElementYEdgeLabel.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_EDGE))
ElementYEdgeLabel.CreateAttr("fontStyle", "plain")
ElementYEdgeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYEdgeLabel.CreateAttr("hasLineColor", "false")
ElementYEdgeLabel.CreateAttr("height", "17.96875")
ElementYEdgeLabel.CreateAttr("horizontalTextPosition", "center")
ElementYEdgeLabel.CreateAttr("iconTextGap", "4")
ElementYEdgeLabel.CreateAttr("modelName", "centered")
ElementYEdgeLabel.CreateAttr("modelPosition", "head")
ElementYEdgeLabel.CreateAttr("preferredPlacement", "anywhere")
//ElementYEdgeLabel.CreateAttr("modelName", "two_pos")
//ElementYEdgeLabel.CreateAttr("modelPosition", "head")
//ElementYEdgeLabel.CreateAttr("preferredPlacement", "on_edge")
ElementYEdgeLabel.CreateAttr("ratio", "0.5")
ElementYEdgeLabel.CreateAttr("textColor", "#000000")
ElementYEdgeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementYEdgeLabel.CreateAttr("visible", "true")
ElementYEdgeLabel.CreateAttr("width", "41.8")
ElementYEdgeLabel.CreateAttr("x", "71.5")
ElementYEdgeLabel.CreateAttr("xml:space", "preserve")
ElementYEdgeLabel.CreateAttr("y", "0.5")
ElementYEdgeLabel.CreateAttr("bottomInset", "0")
ElementYEdgeLabel.CreateAttr("leftInset", "0")
ElementYEdgeLabel.CreateAttr("rightInset", "0")
ElementYEdgeLabel.CreateAttr("topInset", "0")
ElementYEdgeLabel.CreateText(label)
//y:PreferredPlacementDescriptor
ElementYPreferredPlacementDescriptor := ElementYEdgeLabel.CreateElement("y:PreferredPlacementDescriptor")
ElementYPreferredPlacementDescriptor.CreateAttr("angle", "0.0")
ElementYPreferredPlacementDescriptor.CreateAttr("angleOffsetOnRightSide", "0")
ElementYPreferredPlacementDescriptor.CreateAttr("angleReference", "absolute")
ElementYPreferredPlacementDescriptor.CreateAttr("angleRotationOnRightSide", "co")
ElementYPreferredPlacementDescriptor.CreateAttr("distance", "-1.0")
//ElementYPreferredPlacementDescriptor.CreateAttr("frozen", "true")
ElementYPreferredPlacementDescriptor.CreateAttr("placement", "anywhere")
ElementYPreferredPlacementDescriptor.CreateAttr("side", "on_edge")
ElementYPreferredPlacementDescriptor.CreateAttr("sideReference", "relative_to_edge_flow")
//y:BendStyle
ElementYBendStyle := ElementYPolyLineEdge.CreateElement("y:BendStyle")
ElementYBendStyle.CreateAttr("smoothed", "false")
return ElementInfoEdge
}
// CreateElement_Group - создаёт элемент xgml - группа
func CreateElement_Group(ElementInfoGraph types.ElementInfoStruct, GroupCaption string, Width, Height float64) types.ElementInfoStruct {
//Width := FindWidth_Group(GroupCaption)
//Height := FindHeight_Group(GroupCaption)
sWidth := fmt.Sprintf("%.1f", float32(Width))
sHeight := fmt.Sprintf("%.1f", float32(Height))
sWidth = "0.0"
sHeight = "0.0" //авторазмер
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoGraph.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoGraph.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoGroup types.ElementInfoStruct
ElementInfoGroup.Element = ElementNode
ElementInfoGroup.Parent = &ElementInfoGraph
ElementInfoGroup.Name = GroupCaption
ElementInfoGroup.Description = ""
//NodeId := "n" + strconv.Itoa(ElementNode.Index())
NodeId := FindId(ElementInfoGraph, ElementInfoGroup)
ElementNode.CreateAttr("id", NodeId)
ElementNode.CreateAttr("yfiles.foldertype", "group")
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d5")
//YProxyAutoBoundsNode
ElementYProxyAutoBoundsNode := ElementData.CreateElement("y:ProxyAutoBoundsNode")
//YRealizers
ElementYRealizers := ElementYProxyAutoBoundsNode.CreateElement("y:Realizers")
ElementYRealizers.CreateAttr("active", "0")
//----------------------- visible ---------------------------------------------
//YGroupNode
ElementYGroupNode := ElementYRealizers.CreateElement("y:GroupNode")
//YGeometry
ElementYGeometry := ElementYGroupNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", "0.0")
ElementYGeometry.CreateAttr("y", "0.0")
//YFill
ElementYFill := ElementYGroupNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//YBorderStyle
ElementYBorderStyle := ElementYGroupNode.CreateElement("y:BorderStyle")
ElementYBorderStyle.CreateAttr("color", "#F5F5F5")
ElementYBorderStyle.CreateAttr("type", "dashed")
ElementYBorderStyle.CreateAttr("width", "1.0")
//YNodeLabel
ElementYNodeLabel := ElementYGroupNode.CreateElement("y:NodeLabel")
ElementYNodeLabel.CreateAttr("alignment", "right")
ElementYNodeLabel.CreateAttr("autoSizePolicy", "content")
//ElementYNodeLabel.CreateAttr("backgroundColor", "#EBEBEB")
ElementYNodeLabel.CreateAttr("borderDistance", "0.0")
ElementYNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementYNodeLabel.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_GROUP))
ElementYNodeLabel.CreateAttr("fontStyle", "bold")
ElementYNodeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYNodeLabel.CreateAttr("hasLineColor", "false")
ElementYNodeLabel.CreateAttr("height", sHeight)
ElementYNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementYNodeLabel.CreateAttr("iconTextGap", "4")
ElementYNodeLabel.CreateAttr("modelName", "internal")
ElementYNodeLabel.CreateAttr("modelPosition", "t")
ElementYNodeLabel.CreateAttr("textColor", "#000000")
ElementYNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementYNodeLabel.CreateAttr("width", sWidth)
ElementYNodeLabel.CreateAttr("x", "0")
ElementYNodeLabel.CreateAttr("xml:space", "preserve")
ElementYNodeLabel.CreateAttr("y", "0")
ElementYNodeLabel.CreateText(GroupCaption)
//YShape
ElementYShape := ElementYGroupNode.CreateElement("y:Shape")
ElementYShape.CreateAttr("type", "rectangle")
//YState
ElementYState := ElementYGroupNode.CreateElement("y:State")
ElementYState.CreateAttr("closed", "false")
ElementYState.CreateAttr("closedHeight", "80.0")
ElementYState.CreateAttr("closedWidth", "100.0")
ElementYState.CreateAttr("innerGraphDisplayEnabled", "false")
//YInsets
ElementYInsets := ElementYGroupNode.CreateElement("y:Insets")
ElementYInsets.CreateAttr("bottom", "0")
ElementYInsets.CreateAttr("bottomF", "0.0")
ElementYInsets.CreateAttr("left", "0")
ElementYInsets.CreateAttr("leftF", "0.0")
ElementYInsets.CreateAttr("right", "0")
ElementYInsets.CreateAttr("rightF", "0.0")
ElementYInsets.CreateAttr("top", "0")
ElementYInsets.CreateAttr("topF", "0.0")
//YBorderInsets
ElementYBorderInsets := ElementYGroupNode.CreateElement("y:BorderInsets")
ElementYBorderInsets.CreateAttr("bottom", "54")
ElementYBorderInsets.CreateAttr("bottomF", "54.0")
ElementYBorderInsets.CreateAttr("left", "0")
ElementYBorderInsets.CreateAttr("leftF", "0.0")
ElementYBorderInsets.CreateAttr("right", "23")
ElementYBorderInsets.CreateAttr("rightF", "23.35")
ElementYBorderInsets.CreateAttr("top", "0")
ElementYBorderInsets.CreateAttr("topF", "0.0")
//----------------------- not visible ---------------------------------------------
//YGroupNode
ElementYGroupNode2 := ElementYRealizers.CreateElement("y:GroupNode")
//YGeometry
ElementYGeometry2 := ElementYGroupNode2.CreateElement("y:Geometry")
ElementYGeometry2.CreateAttr("height", "40.0")
ElementYGeometry2.CreateAttr("width", sWidth)
ElementYGeometry2.CreateAttr("x", "0.0")
ElementYGeometry2.CreateAttr("y", "0.0")
//YFill
ElementYFill2 := ElementYGroupNode2.CreateElement("y:Fill")
ElementYFill2.CreateAttr("color", "#E8EEF7")
ElementYFill2.CreateAttr("color2", "#B7C9E3")
ElementYFill2.CreateAttr("transparent", "false")
//YBorderStyle
ElementYBorderStyle2 := ElementYGroupNode2.CreateElement("y:BorderStyle")
ElementYBorderStyle2.CreateAttr("color", "#000000")
ElementYBorderStyle2.CreateAttr("type", "dashed")
ElementYBorderStyle2.CreateAttr("width", "1.0")
//YNodeLabel
ElementYNodeLabel2 := ElementYGroupNode2.CreateElement("y:NodeLabel")
ElementYNodeLabel2.CreateAttr("alignment", "right")
ElementYNodeLabel2.CreateAttr("autoSizePolicy", "content")
//ElementYNodeLabel2.CreateAttr("backgroundColor", "#EBEBEB")
ElementYNodeLabel2.CreateAttr("borderDistance", "0.0")
ElementYNodeLabel2.CreateAttr("fontFamily", "Dialog")
ElementYNodeLabel2.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_GROUP))
ElementYNodeLabel2.CreateAttr("fontStyle", "bold")
ElementYNodeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYNodeLabel2.CreateAttr("hasLineColor", "false")
ElementYNodeLabel2.CreateAttr("hasText", "true") //только у 2
ElementYNodeLabel2.CreateAttr("height", sHeight)
ElementYNodeLabel2.CreateAttr("horizontalTextPosition", "center")
ElementYNodeLabel2.CreateAttr("iconTextGap", "4")
ElementYNodeLabel2.CreateAttr("modelName", "internal")
ElementYNodeLabel2.CreateAttr("modelPosition", "t")
ElementYNodeLabel2.CreateAttr("textColor", "#000000")
ElementYNodeLabel2.CreateAttr("verticalTextPosition", "bottom")
ElementYNodeLabel2.CreateAttr("width", sWidth)
ElementYNodeLabel2.CreateAttr("x", "0")
ElementYNodeLabel2.CreateAttr("xml:space", "preserve") //только у 2
ElementYNodeLabel2.CreateAttr("y", "0")
ElementYNodeLabel2.CreateText(GroupCaption) //только у 2
//YShape
ElementYShape2 := ElementYGroupNode2.CreateElement("y:Shape")
ElementYShape2.CreateAttr("type", "roundrectangle")
//YState
ElementYState2 := ElementYGroupNode2.CreateElement("y:State")
ElementYState2.CreateAttr("closed", "true")
ElementYState2.CreateAttr("closedHeight", "80.0")
ElementYState2.CreateAttr("closedWidth", "100.0")
ElementYState2.CreateAttr("innerGraphDisplayEnabled", "false")
//YInsets
ElementYInsets2 := ElementYGroupNode2.CreateElement("y:Insets")
ElementYInsets2.CreateAttr("bottom", "15")
ElementYInsets2.CreateAttr("bottomF", "15.0")
ElementYInsets2.CreateAttr("left", "15")
ElementYInsets2.CreateAttr("leftF", "15.0")
ElementYInsets2.CreateAttr("right", "15")
ElementYInsets2.CreateAttr("rightF", "15.0")
ElementYInsets2.CreateAttr("top", "15")
ElementYInsets2.CreateAttr("topF", "15.0")
//YBorderInsets
ElementYBorderInsets2 := ElementYGroupNode2.CreateElement("y:BorderInsets")
ElementYBorderInsets2.CreateAttr("bottom", "54")
ElementYBorderInsets2.CreateAttr("bottomF", "54.0")
ElementYBorderInsets2.CreateAttr("left", "0")
ElementYBorderInsets2.CreateAttr("leftF", "0.0")
ElementYBorderInsets2.CreateAttr("right", "23")
ElementYBorderInsets2.CreateAttr("rightF", "23.35")
ElementYBorderInsets2.CreateAttr("top", "0")
ElementYBorderInsets2.CreateAttr("topF", "0.0")
//----------------------- продолжение ---------------------------------------------
//YBorderInsets
ElementGraphGraph := ElementNode.CreateElement("graph")
ElementGraphGraph.CreateAttr("edgedefault", "directed")
ElementGraphGraph.CreateAttr("id", NodeId+":")
return ElementInfoGroup
}
// CreateElement_SmallEntity - создаёт элемент - Entity
func CreateElement_SmallEntity(ElementInfoMain types.ElementInfoStruct, ElementName string, Width float64, AttributeIndex int) types.ElementInfoStruct {
//Width := findWidth_SmallEntity(ElementName)
Height := findHeight_SmallEntity(ElementName)
sWidth := fmt.Sprintf("%.1f", float64(Width))
sHeight := fmt.Sprintf("%.1f", float64(Height))
sY := fmt.Sprintf("%.1f", float64(AttributeIndex)*Height)
sFontSize := strconv.Itoa(FONT_SIZE_ENTITY)
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoMain.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoMain.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoNode types.ElementInfoStruct
ElementInfoNode.Element = ElementNode
ElementInfoNode.Name = ElementName
ElementInfoNode.Parent = &ElementInfoMain
ElementInfoNode.Attribute = ""
ElementInfoNode.Width = Width
ElementInfoNode.Height = Height
sId := FindId(ElementInfoMain, ElementInfoNode)
ElementNode.CreateAttr("id", sId)
//ElementNode.CreateAttr("id", "n"+strconv.Itoa(ElementNode.Index()))
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d4")
//data
ElementData2 := ElementNode.CreateElement("data")
ElementData2.CreateAttr("key", "d5")
//y:GenericNode
ElementYGenericNode := ElementData2.CreateElement("y:GenericNode")
ElementYGenericNode.CreateAttr("configuration", "com.yworks.entityRelationship.small_entity")
//YGeometry
ElementYGeometry := ElementYGenericNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", "0")
ElementYGeometry.CreateAttr("y", sY)
//YFill
ElementYFill := ElementYGenericNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//BorderStyle
ElementBorderStyle := ElementYGenericNode.CreateElement("y:BorderStyle")
ElementBorderStyle.CreateAttr("hasColor", "false")
//ElementBorderStyle.CreateAttr("color", "#000000")
ElementBorderStyle.CreateAttr("type", "line")
ElementBorderStyle.CreateAttr("width", "1.0")
//NodeLabel
ElementNodeLabel := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel.CreateAttr("alignment", "left")
ElementNodeLabel.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel.CreateAttr("backgroundColor", "#B7C9E3")
ElementNodeLabel.CreateAttr("borderDistance", "0.0")
ElementNodeLabel.CreateAttr("configuration", "com.yworks.entityRelationship.label.name")
ElementNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel.CreateAttr("fontSize", sFontSize)
ElementNodeLabel.CreateAttr("fontStyle", "plain")
ElementNodeLabel.CreateAttr("hasLineColor", "false")
ElementNodeLabel.CreateAttr("height", sHeight)
ElementNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel.CreateAttr("iconTextGap", "4")
ElementNodeLabel.CreateAttr("modelName", "internal")
ElementNodeLabel.CreateAttr("modelPosition", "tl")
ElementNodeLabel.CreateAttr("textColor", "#000000")
ElementNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementNodeLabel.CreateAttr("visible", "true")
ElementNodeLabel.CreateAttr("width", sWidth)
ElementNodeLabel.CreateAttr("x", "16.0")
ElementNodeLabel.CreateAttr("xml:space", "preserve")
ElementNodeLabel.CreateAttr("y", "4.0")
ElementNodeLabel.CreateText(ElementName)
//y:LabelModel
ElementYLabelModel := ElementNodeLabel.CreateElement("y:LabelModel")
//y:SmartNodeLabelModel
ElementYSmartNodeLabelModel := ElementYLabelModel.CreateElement("y:SmartNodeLabelModel")
ElementYSmartNodeLabelModel.CreateAttr("distance", "0.0")
////y:ErdAttributesNodeLabelModel
//ElementYLabelModel.CreateElement("y:ErdAttributesNodeLabelModel")
////y:ModelParameter
ElementYModelParameter := ElementNodeLabel.CreateElement("y:ModelParameter")
//y:SmartNodeLabelModelParameter
ElementYSmartNodeLabelModelParameter := ElementYModelParameter.CreateElement("y:SmartNodeLabelModelParameter")
ElementYSmartNodeLabelModelParameter.CreateAttr("labelRatioX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("labelRatioY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("nodeRatioX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("nodeRatioY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("offsetX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("offsetY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("upX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("upY", "-1.0")
//y:StyleProperties
ElementYStyleProperties := ElementYGenericNode.CreateElement("y:StyleProperties")
//y:Property
ElementYProperty := ElementYStyleProperties.CreateElement("y:Property")
ElementYProperty.CreateAttr("class", "java.lang.Boolean")
ElementYProperty.CreateAttr("name", "y.view.ShadowNodePainter.SHADOW_PAINTING")
ElementYProperty.CreateAttr("value", "true")
return ElementInfoNode
}
// findWidth_Entity - возвращает число - ширину элемента
func findWidth_Entity(ElementName string) float64 {
var Otvet float64 = float64(FONT_SIZE_ENTITY) * 2
LenMax := findMaxLenRow(ElementName)
//var OtvetF float64
Otvet = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE)*float64(0.48)
//Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Entity - возвращает число - высоту элемента
func findHeight_Entity(ElementName string) float64 {
var Otvet float64
Otvet = float64(12 + FONT_SIZE_ENTITY*3)
RowsTotal := countLines(ElementName)
Otvet = float64(Otvet) + (float64(RowsTotal-1) * math.Round(float64(FONT_SIZE_ENTITY)*float64(1.16)))
return Otvet
}
// findWidth_Bends - возвращает число - ширину элемента
func findWidth_Bends(ElementName string) int {
Otvet := FONT_SIZE_BENDS * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE/2)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Bends - возвращает число - высоту элемента
func findHeight_Bends(ElementName string) int {
Otvet := 10 + FONT_SIZE_BENDS*3
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*FONT_SIZE_SHAPE*2
return Otvet
}
// findWidth_Shape - возвращает число - ширину элемента
func findWidth_Shape(ElementName string) int {
Otvet := FONT_SIZE_SHAPE * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE/2)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Shape - возвращает число - высоту элемента
func findHeight_Shape(ElementName string) int {
Otvet := 10 + FONT_SIZE_SHAPE*3
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*FONT_SIZE_SHAPE*2
return Otvet
}
// findWidth_Group - возвращает число - ширину элемента
func findWidth_Group(ElementName string) int {
Otvet := 10
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*10
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Group - возвращает число - высоту элемента
func findHeight_Group(ElementName string) int {
Otvet := 30
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*18
return Otvet
}
// findWidth_Edge - возвращает число - ширину элемента
func findWidth_Edge(Label string) int {
Otvet := 10
LenMax := findMaxLenRow(Label)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*10
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Edge - возвращает число - высоту элемента
func findHeight_Edge(Label string) int {
Otvet := 30
RowsTotal := countLines(Label)
Otvet = Otvet + (RowsTotal-1)*18
return Otvet
}
// findWidth_SmallEntity - возвращает число - ширину элемента
func findWidth_SmallEntity(ElementName string) int {
Otvet := FONT_SIZE_ENTITY * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE)*float64(0.48)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_SmallEntity - возвращает число - высоту элемента
func findHeight_SmallEntity(ElementName string) float64 {
var Otvet float64
Otvet = float64(6 + FONT_SIZE_ENTITY)
RowsTotal := countLines(ElementName)
Otvet = float64(Otvet) + (float64(RowsTotal-1) * float64(FONT_SIZE_ENTITY))
return Otvet
}
// countLines - возвращает количество переводов строки
func countLines(s string) int {
Otvet := 1
Otvet2 := strings.Count(s, "\n")
Otvet = Otvet + Otvet2
return Otvet
}
// findMaxLenRow - возвращает количество символов в строке максимум
func findMaxLenRow(ElementName string) int {
Otvet := 0
Mass := strings.Split(ElementName, "\n")
for _, Mass1 := range Mass {
MassRune := []rune(Mass1)
len1 := len(MassRune)
if len1 > Otvet {
Otvet = len1
}
}
return Otvet
}
// CreateDocument - создаёт новый документ .xgml
func CreateDocument() (*etree.Document, types.ElementInfoStruct) {
DocXML := etree.NewDocument()
DocXML.CreateProcInst("xml", `version="1.0" encoding="UTF-8" standalone="no"`)
ElementGraphMl := DocXML.CreateElement("graphml")
var ElementInfoGraphML types.ElementInfoStruct
ElementInfoGraphML.Element = ElementGraphMl
ElementInfoGraphML.Parent = nil
ElementGraphMl.CreateAttr("xmlns", "http://graphml.graphdrawing.org/xmlns")
ElementGraphMl.CreateAttr("xmlns:java", "http://www.yworks.com/xml/yfiles-common/1.0/java")
ElementGraphMl.CreateAttr("xmlns:sys", "http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0")
ElementGraphMl.CreateAttr("xmlns:x", "http://www.yworks.com/xml/yfiles-common/markup/2.0")
ElementGraphMl.CreateAttr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
ElementGraphMl.CreateAttr("xmlns:y", "http://www.yworks.com/xml/graphml")
ElementGraphMl.CreateAttr("xmlns:y", "http://www.yworks.com/xml/graphml")
ElementGraphMl.CreateAttr("xmlns:yed", "http://www.yworks.com/xml/yed/3")
ElementGraphMl.CreateAttr("xsi:schemaLocation", "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd")
ElementD0 := ElementGraphMl.CreateElement("key")
ElementD0.CreateAttr("for", "port")
ElementD0.CreateAttr("id", "d0")
ElementD0.CreateAttr("yfiles.type", "portgraphics")
ElementD1 := ElementGraphMl.CreateElement("key")
ElementD1.CreateAttr("for", "port")
ElementD1.CreateAttr("id", "d1")
ElementD1.CreateAttr("yfiles.type", "portgeometry")
ElementD2 := ElementGraphMl.CreateElement("key")
ElementD2.CreateAttr("for", "port")
ElementD2.CreateAttr("id", "d2")
ElementD2.CreateAttr("yfiles.type", "portuserdata")
ElementD3 := ElementGraphMl.CreateElement("key")
ElementD3.CreateAttr("attr.name", "url")
ElementD3.CreateAttr("attr.type", "string")
ElementD3.CreateAttr("for", "node")
ElementD3.CreateAttr("id", "d3")
ElementD4 := ElementGraphMl.CreateElement("key")
ElementD4.CreateAttr("attr.name", "description")
ElementD4.CreateAttr("attr.type", "string")
ElementD4.CreateAttr("for", "node")
ElementD4.CreateAttr("id", "d4")
ElementD5 := ElementGraphMl.CreateElement("key")
ElementD5.CreateAttr("for", "node")
ElementD5.CreateAttr("id", "d5")
ElementD5.CreateAttr("yfiles.type", "nodegraphics")
ElementD6 := ElementGraphMl.CreateElement("key")
ElementD6.CreateAttr("for", "graphml")
ElementD6.CreateAttr("id", "d6")
ElementD6.CreateAttr("yfiles.type", "resources")
ElementD7 := ElementGraphMl.CreateElement("key")
ElementD7.CreateAttr("attr.name", "url")
ElementD7.CreateAttr("attr.type", "string")
ElementD7.CreateAttr("for", "edge")
ElementD7.CreateAttr("id", "d7")
ElementD8 := ElementGraphMl.CreateElement("key")
ElementD8.CreateAttr("attr.name", "description")
ElementD8.CreateAttr("attr.type", "string")
ElementD8.CreateAttr("for", "edge")
ElementD8.CreateAttr("id", "d8")
ElementD9 := ElementGraphMl.CreateElement("key")
ElementD9.CreateAttr("for", "edge")
ElementD9.CreateAttr("id", "d9")
ElementD9.CreateAttr("yfiles.type", "edgegraphics")
ElementGraph := ElementGraphMl.CreateElement("graph")
ElementGraph.CreateAttr("edgedefault", "directed")
ElementGraph.CreateAttr("id", "G")
return DocXML, ElementInfoGraphML
}
// FindId - находит ИД в формате "n1::n1::n1"
func FindId(ElementInfoMain, ElementInfo types.ElementInfoStruct) string {
Otvet := ""
//if Element == nil {
// return Otvet
//}
//if Element == ElementGraph0 {
// return Otvet
//}
if ElementInfo.Element.Tag == "node" {
Otvet = "n" + strconv.Itoa(ElementInfo.Element.Index())
//return Otvet
}
ParentSID := ""
if ElementInfo.Parent != nil {
ParentSID = FindId(ElementInfoMain, *ElementInfo.Parent)
}
if ParentSID != "" {
if Otvet == "" {
Otvet = ParentSID
} else {
Otvet = ParentSID + "::" + Otvet
}
}
return Otvet
}

140
pkg/graphml/graphml_read.go Normal file
View File

@ -0,0 +1,140 @@
package graphml
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/micro"
"github.com/beevik/etree"
"strconv"
)
func ReadFile(Filename string) (*etree.Document, error) {
var err error
doc := etree.NewDocument()
err = doc.ReadFromFile(Filename)
if err != nil {
log.Panic(err)
}
return doc, err
}
func FindMassElement(doc *etree.Document) []*etree.Element {
MassElement := make([]*etree.Element, 0)
ElementGraphMl := doc.SelectElement("graphml")
ElementGraph := ElementGraphMl.SelectElement("graph")
MassElement = ElementGraph.SelectElements("node")
return MassElement
}
func FindMapNodeStruct(MassElement []*etree.Element) map[string]types.NodeStruct {
MapNodeStruct := make(map[string]types.NodeStruct, 0)
var err error
for _, ElementNode1 := range MassElement {
sx := ""
sy := ""
Name := ""
MassData := ElementNode1.SelectElements("data")
if len(MassData) == 0 {
continue
}
var ElementData1 *etree.Element
ElementData1 = MassData[len(MassData)-1]
//for _, ElementData1 = range MassData {
//key := ElementData1.SelectAttrValue("key", "")
//if key != "d5" {
// continue
//}
ElementGenericNode := ElementData1.SelectElement("y:GenericNode")
if ElementGenericNode == nil {
continue
}
ElementGeometry := ElementGenericNode.SelectElement("y:Geometry")
if ElementGeometry == nil {
continue
}
sx = ElementGeometry.SelectAttrValue("x", "0")
sy = ElementGeometry.SelectAttrValue("y", "0")
ElementNodeLabel := ElementGenericNode.SelectElement("y:NodeLabel")
if ElementNodeLabel == nil {
continue
}
Name = ElementNodeLabel.Text()
if Name == "" {
log.Warn("Name = ''")
continue
}
var x float64
if sx != "" {
x, err = strconv.ParseFloat(sx, 32)
if err != nil {
log.Warn("Name: ", Name+" ParseFloat(", sx, ") error: ", err)
}
}
var y float64
if sy != "" {
y, err = strconv.ParseFloat(sy, 32)
if err != nil {
log.Warn("Name: ", Name+" ParseFloat(", sy, ") error: ", err)
}
}
NodeStruct1 := types.NodeStruct{}
NodeStruct1.Element = ElementNode1
NodeStruct1.Name = Name
NodeStruct1.X = x
NodeStruct1.Y = y
MapNodeStruct[Name] = NodeStruct1
//}
}
return MapNodeStruct
}
// StartReadFile - читает старый файл в
func StartReadFile() {
//dir := micro.ProgramDir()
//Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
Filename := config.Settings.FILENAME_GRAPHML
ok, err := micro.FileExists(Filename)
if ok == false {
return
}
doc, err := ReadFile(Filename)
if err != nil {
log.Error("ReadFile() error: ", err)
return
}
if doc == nil {
log.Error("ReadFile() error: doc =nil")
return
}
MassElement := FindMassElement(doc)
if len(MassElement) == 0 {
log.Warn("FindMassElement() error: len =0")
return
}
types.MapNodeStructOld = FindMapNodeStruct(MassElement)
if len(types.MapNodeStructOld) == 0 {
log.Warn("FindMapNodeStruct() error: len =0")
return
}
}

View File

@ -0,0 +1,67 @@
package graphml
import (
"github.com/ManyakRus/crud_generator/internal/config"
ConfigMain "github.com/ManyakRus/starter/config"
"github.com/ManyakRus/starter/micro"
"testing"
)
func TestReadFile(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestReadFile() error: ", err)
}
if doc == nil {
t.Error("TestReadFile() error: doc =nil")
}
}
func TestFindMassEntity(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestFindMassEntity() error: ", err)
}
if doc == nil {
t.Error("TestFindMassEntity() error: doc =nil")
}
Otvet := FindMassElement(doc)
if len(Otvet) == 0 {
t.Error("TestFindMassEntity() error: len =0")
}
}
func TestFindMapNodeStruct(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestFindMapNodeStruct() error: ", err)
}
if doc == nil {
t.Error("TestFindMapNodeStruct() error: doc =nil")
}
MassElement := FindMassElement(doc)
if len(MassElement) == 0 {
t.Error("TestFindMapNodeStruct() error: len =0")
}
Otvet := FindMapNodeStruct(MassElement)
if len(Otvet) == 0 {
t.Error("TestFindMapNodeStruct() error: ", err)
}
}
func TestStartReadFile(t *testing.T) {
ConfigMain.LoadEnv()
config.FillSettings()
StartReadFile()
}

View File

@ -0,0 +1,32 @@
package graphml
import (
"github.com/ManyakRus/starter/micro"
"testing"
)
func TestCreateNewGraphml(t *testing.T) {
dir := micro.ProgramDir()
DocXML, ElementGraph := CreateDocument()
Entity1 := CreateElement_Entity(ElementGraph, "Entity1", "Field1\nField2\nField3\n1234567890")
Entity2 := CreateElement_Entity(ElementGraph, "Entity2", "Field1\nField2\nField3\n1234567890")
CreateElement_Edge(ElementGraph, Entity1, Entity2, "edge1", "descr", 4, 1)
//Shape2 := CreateElement_Shape(ElementGraph, "Shape2")
//Group1 := CreateElement_Group(ElementGraph, "Group1")
//Shape1 := CreateElement_Shape(Group1, "Shape1")
//CreateElement_Edge(ElementGraph, Shape1, Shape2, "edge1", "descr")
//CreateElement_Edge_blue(ElementGraph, Shape2, Shape1, "edge2", "descr2")
//
//if Shape1 == nil || Shape2 == nil {
//
//}
FileName := dir + "test" + micro.SeparatorFile() + "test.graphml"
//DocXML.IndentTabs()
DocXML.Indent(2)
err := DocXML.WriteToFile(FileName)
if err != nil {
t.Error("TestCreateNewXGML() error: ", err)
}
}

32
settings/connections.txt Normal file
View File

@ -0,0 +1,32 @@
{
"github.com/segmentio/kafka-go": "Kafka",
"gorm.io/driver/postgres": "Postgres",
"github.com/camunda/zeebe/clients/go/v8": "Camunda",
"gitlab.aescorp.ru/dsp_dev/claim/nikitin/nats_connect": "Nats",
"github.com/nats-io/nats.go": "Nats",
"github.com/minio/minio-go": "Minio",
"github.com/sashabaranov/go-openai": "Chat GPT",
"github.com/xhit/go-simple-mail": "EMail server",
"github.com/emersion/go-imap": "EMail IMAP server",
"github.com/denisenkom/go-mssqldb": "MSSQL",
"github.com/lib/pq": "Postgres",
"github.com/jackc/pgx": "Postgres",
"github.com/gotd": "Telegram",
"go.mau.fi/whatsmeow": "Whatsapp",
"github.com/mattn/go-sqlite3": "SQL Lite3",
"net/http": "WEB",
"github.com/valyala/fasthttp": "WEB",
"github.com/gin-gonic/gin": "WEB",
"github.com/rabbitmq/amqp091-go": "RabbitMQ",
"github.com/ManyakRus/starter/kafka_connect": "Kafka",
"github.com/ManyakRus/starter/postgres_gorm": "Postgres",
"github.com/ManyakRus/starter/camunda_connect": "Camunda",
"github.com/ManyakRus/starter/nats_connect": "Nats",
"github.com/ManyakRus/starter/minio_connect": "Minio",
"github.com/ManyakRus/starter/liveness": "WEB server\nLiveness",
"github.com/ManyakRus/starter/whatsapp_connect": "Whatsapp",
"github.com/go-redis/redis": "Redis",
"github.com/gorilla/websocket": "Web socket",
"github.com/Nerzal/gocloak": "Keycloak",
"github.com/prometheus/client_golang/prometheus/promhttp": "Prometeus"
}

View File

@ -0,0 +1,4 @@
{
"Service1": "github.com/ManyakRus/1",
"Service2": "github.com/ManyakRus/2"
}

79
test/test.graphml Normal file
View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="117.0" width="109.0" x="-270.0" y="-65.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="117.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="109.0" x="16.0" xml:space="preserve" y="4.0">Entity1</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="117.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="109.0" x="2.0" xml:space="preserve" y="30.0">Field1
Field2
Field3
1234567890
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n1">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="117.0" width="109.0" x="-270.0" y="-65.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="117.0" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="109.0" x="16.0" xml:space="preserve" y="4.0">Entity2</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="117.0" horizontalTextPosition="center" iconTextGap="4" modelName="free" modelPosition="anywhere" textColor="#000000" verticalTextPosition="top" visible="true" width="109.0" x="2.0" xml:space="preserve" y="30.0">Field1
Field2
Field3
1234567890
<y:LabelModel>
<y:ErdAttributesNodeLabelModel/>
</y:LabelModel>
<y:ModelParameter>
<y:ErdAttributesNodeLabelModelParameter/>
</y:ModelParameter>
</y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
</graph>
<edge id="e11" source="n0" target="n1">
<data key="d8" xml:space="preserve"><![CDATA[descr]]></data>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-54.0" sy="39.1" tx="54.0" ty="-18.5"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="0.0" fontFamily="Dialog" fontSize="8" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="centered" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="41.8" x="71.5" xml:space="preserve" y="0.5" bottomInset="0" leftInset="0" rightInset="0" topInset="0">edge1
<y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" placement="anywhere" side="on_edge" sideReference="relative_to_edge_flow"/>
</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graphml>

View File

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.21.1-->
<key for="port" id="d0" yfiles.type="portgraphics"/>
<key for="port" id="d1" yfiles.type="portgeometry"/>
<key for="port" id="d2" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d3"/>
<key attr.name="description" attr.type="string" for="node" id="d4"/>
<key for="node" id="d5" yfiles.type="nodegraphics"/>
<key for="graphml" id="d6" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d7"/>
<key attr.name="description" attr.type="string" for="edge" id="d8"/>
<key for="edge" id="d9" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<node id="n0">
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.big_entity">
<y:Geometry height="90.0" width="80.0" x="-58.5" y="-65.0"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" backgroundColor="#B7C9E3" configuration="com.yworks.entityRelationship.label.name" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="46.66796875" x="16.666015625" xml:space="preserve" y="4.0">Entity2</y:NodeLabel>
<y:NodeLabel alignment="left" autoSizePolicy="content" configuration="com.yworks.entityRelationship.label.attributes" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="45.90625" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="top" visible="true" width="67.791015625" x="2.0" xml:space="preserve" y="29.96875">attribute 1
attribute 2
attribute 3<y:LabelModel><y:ErdAttributesNodeLabelModel/></y:LabelModel><y:ModelParameter><y:ErdAttributesNodeLabelModelParameter/></y:ModelParameter></y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n1" yfiles.foldertype="group">
<data key="d3" xml:space="preserve"/>
<data key="d4"/>
<data key="d5">
<y:ProxyAutoBoundsNode>
<y:Realizers active="0">
<y:GroupNode>
<y:Geometry height="67.02968750000002" width="90.0" x="119.79999999999995" y="-252.31484375000002"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="node_width" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="90.0" x="0.0" xml:space="preserve" y="0.0">Entity1</y:NodeLabel>
<y:Shape type="rectangle"/>
<y:State closed="false" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="5" bottomF="5.0" left="5" leftF="5.0" right="5" rightF="5.0" top="5" topF="5.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
<y:GroupNode>
<y:Geometry height="94.23679999999999" width="126.34943999999999" x="-265.0" y="-299.775968"/>
<y:Fill color="#F2F0D8" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#B7B69E" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="126.34943999999999" x="0.0" xml:space="preserve" y="0.0">3</y:NodeLabel>
<y:Shape type="rectangle"/>
<y:DropShadow color="#D2D2D2" offsetX="4" offsetY="4"/>
<y:State closed="true" closedHeight="94.23679999999999" closedWidth="126.34943999999999" innerGraphDisplayEnabled="false"/>
<y:Insets bottom="5" bottomF="5.0" left="5" leftF="5.0" right="5" rightF="5.0" top="5" topF="5.0"/>
<y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
</y:GroupNode>
</y:Realizers>
</y:ProxyAutoBoundsNode>
</data>
<graph edgedefault="directed" id="n1:">
<node id="n1::n0">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.small_entity">
<y:Geometry height="17.600000000000023" width="80.0" x="124.79999999999995" y="-225.66953125000003"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle hasColor="false" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="64.83203125" x="7.583984375" xml:space="preserve" y="-0.18437499999998863">Attribute1<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
<node id="n1::n1">
<data key="d4"/>
<data key="d5">
<y:GenericNode configuration="com.yworks.entityRelationship.small_entity">
<y:Geometry height="17.600000000000023" width="80.0" x="124.79999999999995" y="-208.06953125"/>
<y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
<y:BorderStyle hasColor="false" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="64.83203125" x="7.583984375" xml:space="preserve" y="-0.18437499999998863">Attribute2<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
<y:StyleProperties>
<y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
</y:StyleProperties>
</y:GenericNode>
</data>
</node>
</graph>
</node>
<edge id="e0" source="n1::n1" target="n0">
<data key="d8"/>
<data key="d9">
<y:PolyLineEdge>
<y:Path sx="-39.990234375" sy="0.0" tx="-40.00264814559853" ty="-6.761586816715692"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="crows_foot_many" target="none"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graph>
<data key="d6">
<y:Resources/>
</data>
</graphml>

4
vendor/github.com/ManyakRus/logrus/.gitignore generated vendored Normal file
View File

@ -0,0 +1,4 @@
logrus
vendor
.idea/

40
vendor/github.com/ManyakRus/logrus/.golangci.yml generated vendored Normal file
View File

@ -0,0 +1,40 @@
run:
# do not run on test files yet
tests: false
# all available settings of specific linters
linters-settings:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: false
lll:
line-length: 100
tab-width: 4
prealloc:
simple: false
range-loops: false
for-loops: false
whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
linters:
enable:
- megacheck
- govet
disable:
- maligned
- prealloc
disable-all: false
presets:
- bugs
- unused
fast: false

15
vendor/github.com/ManyakRus/logrus/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,15 @@
language: go
go_import_path: github.com/sirupsen/logrus
git:
depth: 1
env:
- GO111MODULE=on
go: 1.15.x
os: linux
install:
- ./travis/install.sh
script:
- cd ci
- go run mage.go -v -w ../ crossBuild
- go run mage.go -v -w ../ lint
- go run mage.go -v -w ../ test

259
vendor/github.com/ManyakRus/logrus/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,259 @@
# 1.8.1
Code quality:
* move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer
* improve timestamp format documentation
Fixes:
* fix race condition on logger hooks
# 1.8.0
Correct versioning number replacing v1.7.1.
# 1.7.1
Beware this release has introduced a new public API and its semver is therefore incorrect.
Code quality:
* use go 1.15 in travis
* use magefile as task runner
Fixes:
* small fixes about new go 1.13 error formatting system
* Fix for long time race condiction with mutating data hooks
Features:
* build support for zos
# 1.7.0
Fixes:
* the dependency toward a windows terminal library has been removed
Features:
* a new buffer pool management API has been added
* a set of `<LogLevel>Fn()` functions have been added
# 1.6.0
Fixes:
* end of line cleanup
* revert the entry concurrency bug fix whic leads to deadlock under some circumstances
* update dependency on go-windows-terminal-sequences to fix a crash with go 1.14
Features:
* add an option to the `TextFormatter` to completely disable fields quoting
# 1.5.0
Code quality:
* add golangci linter run on travis
Fixes:
* add mutex for hooks concurrent access on `Entry` data
* caller function field for go1.14
* fix build issue for gopherjs target
Feature:
* add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level
* add a `DisableHTMLEscape` option in the `JSONFormatter`
* add `ForceQuote` and `PadLevelText` options in the `TextFormatter`
# 1.4.2
* Fixes build break for plan9, nacl, solaris
# 1.4.1
This new release introduces:
* Enhance TextFormatter to not print caller information when they are empty (#944)
* Remove dependency on golang.org/x/crypto (#932, #943)
Fixes:
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
# 1.4.0
This new release introduces:
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
Fixes:
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
* Fix infinite recursion on unknown `Level.String()` (#907)
* Fix race condition in `getCaller` (#916).
# 1.3.0
This new release introduces:
* Log, Logf, Logln functions for Logger and Entry that take a Level
Fixes:
* Building prometheus node_exporter on AIX (#840)
* Race condition in TextFormatter (#468)
* Travis CI import path (#868)
* Remove coloured output on Windows (#862)
* Pointer to func as field in JSONFormatter (#870)
* Properly marshal Levels (#873)
# 1.2.0
This new release introduces:
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
* A new trace level named `Trace` whose level is below `Debug`
* A configurable exit function to be called upon a Fatal trace
* The `Level` object now implements `encoding.TextUnmarshaler` interface
# 1.1.1
This is a bug fix release.
* fix the build break on Solaris
* don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized
# 1.1.0
This new release introduces:
* several fixes:
* a fix for a race condition on entry formatting
* proper cleanup of previously used entries before putting them back in the pool
* the extra new line at the end of message in text formatter has been removed
* a new global public API to check if a level is activated: IsLevelEnabled
* the following methods have been added to the Logger object
* IsLevelEnabled
* SetFormatter
* SetOutput
* ReplaceHooks
* introduction of go module
* an indent configuration for the json formatter
* output colour support for windows
* the field sort function is now configurable for text formatter
* the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
# 1.0.6
This new release introduces:
* a new api WithTime which allows to easily force the time of the log entry
which is mostly useful for logger wrapper
* a fix reverting the immutability of the entry given as parameter to the hooks
a new configuration field of the json formatter in order to put all the fields
in a nested dictionnary
* a new SetOutput method in the Logger
* a new configuration of the textformatter to configure the name of the default keys
* a new configuration of the text formatter to disable the level truncation
# 1.0.5
* Fix hooks race (#707)
* Fix panic deadlock (#695)
# 1.0.4
* Fix race when adding hooks (#612)
* Fix terminal check in AppEngine (#635)
# 1.0.3
* Replace example files with testable examples
# 1.0.2
* bug: quote non-string values in text formatter (#583)
* Make (*Logger) SetLevel a public method
# 1.0.1
* bug: fix escaping in text formatter (#575)
# 1.0.0
* Officially changed name to lower-case
* bug: colors on Windows 10 (#541)
* bug: fix race in accessing level (#512)
# 0.11.5
* feature: add writer and writerlevel to entry (#372)
# 0.11.4
* bug: fix undefined variable on solaris (#493)
# 0.11.3
* formatter: configure quoting of empty values (#484)
* formatter: configure quoting character (default is `"`) (#484)
* bug: fix not importing io correctly in non-linux environments (#481)
# 0.11.2
* bug: fix windows terminal detection (#476)
# 0.11.1
* bug: fix tty detection with custom out (#471)
# 0.11.0
* performance: Use bufferpool to allocate (#370)
* terminal: terminal detection for app-engine (#343)
* feature: exit handler (#375)
# 0.10.0
* feature: Add a test hook (#180)
* feature: `ParseLevel` is now case-insensitive (#326)
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
* performance: avoid re-allocations on `WithFields` (#335)
# 0.9.0
* logrus/text_formatter: don't emit empty msg
* logrus/hooks/airbrake: move out of main repository
* logrus/hooks/sentry: move out of main repository
* logrus/hooks/papertrail: move out of main repository
* logrus/hooks/bugsnag: move out of main repository
* logrus/core: run tests with `-race`
* logrus/core: detect TTY based on `stderr`
* logrus/core: support `WithError` on logger
* logrus/core: Solaris support
# 0.8.7
* logrus/core: fix possible race (#216)
* logrus/doc: small typo fixes and doc improvements
# 0.8.6
* hooks/raven: allow passing an initialized client
# 0.8.5
* logrus/core: revert #208
# 0.8.4
* formatter/text: fix data race (#218)
# 0.8.3
* logrus/core: fix entry log level (#208)
* logrus/core: improve performance of text formatter by 40%
* logrus/core: expose `LevelHooks` type
* logrus/core: add support for DragonflyBSD and NetBSD
* formatter/text: print structs more verbosely
# 0.8.2
* logrus: fix more Fatal family functions
# 0.8.1
* logrus: fix not exiting on `Fatalf` and `Fatalln`
# 0.8.0
* logrus: defaults to stderr instead of stdout
* hooks/sentry: add special field for `*http.Request`
* formatter/text: ignore Windows for colors
# 0.7.3
* formatter/\*: allow configuration of timestamp layout
# 0.7.2
* formatter/text: Add configuration option for time format (#158)

21
vendor/github.com/ManyakRus/logrus/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Simon Eskildsen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

515
vendor/github.com/ManyakRus/logrus/README.md generated vendored Normal file
View File

@ -0,0 +1,515 @@
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger.
**Logrus is in maintenance-mode.** We will not be introducing new features. It's
simply too hard to do in a way that won't break many people's projects, which is
the last thing you want from your Logging library (again...).
This does not mean Logrus is dead. Logrus will continue to be maintained for
security, (backwards compatible) bug fixes, and performance (where we are
limited by the interface).
I believe Logrus' biggest contribution is to have played a part in today's
widespread use of structured logging in Golang. There doesn't seem to be a
reason to do a major, breaking iteration into Logrus V2, since the fantastic Go
community has built those independently. Many fantastic alternatives have sprung
up. Logrus would look like those, had it been re-designed with what we know
about structured logging in Go today. Check out, for example,
[Zerolog][zerolog], [Zap][zap], and [Apex][apex].
[zerolog]: https://github.com/rs/zerolog
[zap]: https://github.com/uber-go/zap
[apex]: https://github.com/apex/log
**Seeing weird case-sensitive problems?** It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments
experienced problems with the upper-case variant, so the lower-case was decided.
Everything using `logrus` will need to use the lower-case:
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
To fix Glide, see [these
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
For an in-depth explanation of the casing issue, see [this
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):
![Colored](http://i.imgur.com/PY7qMwd.png)
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
or Splunk:
```json
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
{"level":"warning","msg":"The group's number increased tremendously!",
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
```
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
attached, the output is compatible with the
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
```text
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
```
To ensure this behaviour even if a TTY is attached, set your formatter as follows:
```go
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
```
#### Logging Method Name
If you wish to add the calling method as a field, instruct the logger via:
```go
log.SetReportCaller(true)
```
This adds the caller as 'method' like so:
```json
{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
```
```text
time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
```
Note that this does add measurable overhead - the cost will depend on the version of Go, but is
between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
environment via benchmarks:
```
go test -bench=.*CallerTracing
```
#### Case-sensitivity
The organization's name was changed to lower-case--and this will not be changed
back. If you are getting import conflicts due to case sensitivity, please use
the lower-case import: `github.com/sirupsen/logrus`.
#### Example
The simplest way to use Logrus is simply the package-level exported logger:
```go
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
```
Note that it's completely api-compatible with the stdlib logger, so you can
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
and you'll now have the flexibility of Logrus. You can customize it all you
want:
```go
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
// A common pattern is to re-use fields between logging statements by re-using
// the logrus.Entry returned from WithFields()
contextLogger := log.WithFields(log.Fields{
"common": "this is a common field",
"other": "I also should be logged always",
})
contextLogger.Info("I'll be logged with common and other field")
contextLogger.Info("Me too")
}
```
For more advanced usage such as logging to multiple locations from the same
application, you can also create an instance of the `logrus` Logger:
```go
package main
import (
"os"
"github.com/sirupsen/logrus"
)
// Create a new instance of the logger. You can have any number of instances.
var log = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
log.Out = os.Stdout
// You could set this to any `io.Writer` such as a file
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// if err == nil {
// log.Out = file
// } else {
// log.Info("Failed to log to file, using default stderr")
// }
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
```
#### Fields
Logrus encourages careful, structured logging through logging fields instead of
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
to send event %s to topic %s with key %d")`, you should log the much more
discoverable:
```go
log.WithFields(log.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
```
We've found this API forces you to think about logging in a way that produces
much more useful logging messages. We've been in countless situations where just
a single added field to a log statement that was already there would've saved us
hours. The `WithFields` call is optional.
In general, with Logrus using any of the `printf`-family functions should be
seen as a hint you should add a field, however, you can still use the
`printf`-family functions with Logrus.
#### Default Fields
Often it's helpful to have fields _always_ attached to log statements in an
application or parts of one. For example, you may want to always log the
`request_id` and `user_ip` in the context of a request. Instead of writing
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
every line, you can create a `logrus.Entry` to pass around instead:
```go
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")
```
#### Hooks
You can add hooks for logging levels. For example to send errors to an exception
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
multiple places simultaneously, e.g. syslog.
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
`init`:
```go
import (
log "github.com/sirupsen/logrus"
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
"log/syslog"
)
func init() {
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
log.Error("Unable to connect to local syslog daemon")
} else {
log.AddHook(hook)
}
}
```
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
#### Level logging
Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
```go
log.Trace("Something very low level.")
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")
```
You can set the logging level on a `Logger`, then it will only log entries with
that severity or anything above it:
```go
// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)
```
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
environment if your application has that.
Note: If you want different log levels for global (`log.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging).
#### Entries
Besides the fields added with `WithField` or `WithFields` some fields are
automatically added to all logging events:
1. `time`. The timestamp when the entry was created.
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
the `AddFields` call. E.g. `Failed to send event.`
3. `level`. The logging level. E.g. `info`.
#### Environments
Logrus has no notion of environment.
If you wish for hooks and formatters to only be used in specific environments,
you should handle that yourself. For example, if your application has a global
variable `Environment`, which is a string representation of the environment you
could do:
```go
import (
log "github.com/sirupsen/logrus"
)
func init() {
// do something here to set environment depending on an environment variable
// or command-line flag
if Environment == "production" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// The TextFormatter is default, you don't actually have to do this.
log.SetFormatter(&log.TextFormatter{})
}
}
```
This configuration is how `logrus` was intended to be used, but JSON in
production is mostly only useful if you do log aggregation with tools like
Splunk or Logstash.
#### Formatters
The built-in logging formatters are:
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
without colors.
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
field to `true`. To force no colored output even if there is a TTY set the
`DisableColors` field to `true`. For Windows, see
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
* When colors are enabled, levels are truncated to 4 characters by default. To disable
truncation set the `DisableLevelTruncation` field to `true`.
* When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
* `logrus.JSONFormatter`. Logs fields as JSON.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
Third party logging formatters:
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo.
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files.
* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
`Fields` type (`map[string]interface{}`) with all your fields as well as the
default ones (see Entries section above):
```go
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err)
}
return append(serialized, '\n'), nil
}
```
#### Logger as an `io.Writer`
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
```go
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
```
Each line written to that writer will be printed the usual way, using formatters
and hooks. The level for those entries is `info`.
This means that we can override the standard library logger easily:
```go
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
```
#### Rotation
Log rotation is not provided with Logrus. Log rotation should be done by an
external program (like `logrotate(8)`) that can compress and delete old log
entries. It should not be a feature of the application-level logger.
#### Tools
| Tool | Description |
| ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
#### Testing
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go
import(
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"testing"
)
func TestSomething(t*testing.T){
logger, hook := test.NewNullLogger()
logger.Error("Helloerror")
assert.Equal(t, 1, len(hook.Entries))
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
hook.Reset()
assert.Nil(t, hook.LastEntry())
}
```
#### Fatal handlers
Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before
logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
```
...
handler := func() {
// gracefully shutdown something...
}
logrus.RegisterExitHandler(handler)
...
```
#### Thread safety
By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
Situation when locking is not needed includes:
* You have no hooks registered, or hooks calling is already thread-safe.
* Writing to logger.Out is already thread-safe, for example:
1) logger.Out is protected by locks.
2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing)
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)

76
vendor/github.com/ManyakRus/logrus/alt_exit.go generated vendored Normal file
View File

@ -0,0 +1,76 @@
package logrus
// The following code was sourced and modified from the
// https://github.com/tebeka/atexit package governed by the following license:
//
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import (
"fmt"
"os"
)
var handlers = []func(){}
func runHandler(handler func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
}
}()
handler()
}
func runHandlers() {
for _, handler := range handlers {
runHandler(handler)
}
}
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
func Exit(code int) {
runHandlers()
os.Exit(code)
}
// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler)
}
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func DeferExitHandler(handler func()) {
handlers = append([]func(){handler}, handlers...)
}

14
vendor/github.com/ManyakRus/logrus/appveyor.yml generated vendored Normal file
View File

@ -0,0 +1,14 @@
version: "{build}"
platform: x64
clone_folder: c:\gopath\src\github.com\sirupsen\logrus
environment:
GOPATH: c:\gopath
branches:
only:
- master
install:
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- go version
build_script:
- go get -t
- go test

43
vendor/github.com/ManyakRus/logrus/buffer_pool.go generated vendored Normal file
View File

@ -0,0 +1,43 @@
package logrus
import (
"bytes"
"sync"
)
var (
bufferPool BufferPool
)
type BufferPool interface {
Put(*bytes.Buffer)
Get() *bytes.Buffer
}
type defaultPool struct {
pool *sync.Pool
}
func (p *defaultPool) Put(buf *bytes.Buffer) {
p.pool.Put(buf)
}
func (p *defaultPool) Get() *bytes.Buffer {
return p.pool.Get().(*bytes.Buffer)
}
// SetBufferPool allows to replace the default logrus buffer pool
// to better meets the specific needs of an application.
func SetBufferPool(bp BufferPool) {
bufferPool = bp
}
func init() {
SetBufferPool(&defaultPool{
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
})
}

26
vendor/github.com/ManyakRus/logrus/doc.go generated vendored Normal file
View File

@ -0,0 +1,26 @@
/*
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
The simplest way to use Logrus is simply the package-level exported logger:
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
}).Info("A walrus appears")
}
Output:
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
For a full guide visit https://github.com/sirupsen/logrus
*/
package logrus

443
vendor/github.com/ManyakRus/logrus/entry.go generated vendored Normal file
View File

@ -0,0 +1,443 @@
package logrus
import (
"bytes"
"context"
"fmt"
"os"
"reflect"
"runtime"
"strings"
"sync"
"time"
)
var (
// qualified package name, cached at first use
logrusPackage string
// Positions in the call stack when tracing to report the calling method
minimumCallerDepth int
// Used for caller information initialisation
callerInitOnce sync.Once
)
const (
maximumCallerDepth int = 25
knownLogrusFrames int = 4
)
func init() {
// start at the bottom of the stack before the package-name cache is primed
minimumCallerDepth = 1
}
// Defines the key when adding errors using WithError.
var ErrorKey = "error"
// An entry is the final or intermediate Logrus logging entry. It contains all
// the fields passed with WithField{,s}. It's finally logged when Trace, Debug,
// Info, Warn, Error, Fatal or Panic is called on it. These objects can be
// reused and passed around as much as you wish to avoid field duplication.
type Entry struct {
Logger *Logger
// Contains all the fields set by the user.
Data Fields
// Time at which the log entry was created
Time time.Time
// Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
// This field will be set on entry firing and the value will be equal to the one in Logger struct field.
Level Level
// Calling method, with package name
Caller *runtime.Frame
// Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
Message string
// When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer
// Contains the context set by the user. Useful for hook processing etc.
Context context.Context
// err may contain a field formatting error
err string
}
func NewEntry(logger *Logger) *Entry {
return &Entry{
Logger: logger,
// Default is three fields, plus one optional. Give a little extra room.
Data: make(Fields, 6),
}
}
func (entry *Entry) Dup() *Entry {
data := make(Fields, len(entry.Data))
for k, v := range entry.Data {
data[k] = v
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err}
}
// Returns the bytes representation of this entry from the formatter.
func (entry *Entry) Bytes() ([]byte, error) {
return entry.Logger.Formatter.Format(entry)
}
// Returns the string representation from the reader and ultimately the
// formatter.
func (entry *Entry) String() (string, error) {
serialized, err := entry.Bytes()
if err != nil {
return "", err
}
str := string(serialized)
return str, nil
}
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
func (entry *Entry) WithError(err error) *Entry {
return entry.WithField(ErrorKey, err)
}
// Add a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx}
}
// Add a single field to the Entry.
func (entry *Entry) WithField(key string, value interface{}) *Entry {
return entry.WithFields(Fields{key: value})
}
// Add a map of fields to the Entry.
func (entry *Entry) WithFields(fields Fields) *Entry {
data := make(Fields, len(entry.Data)+len(fields))
for k, v := range entry.Data {
data[k] = v
}
fieldErr := entry.err
for k, v := range fields {
isErrField := false
if t := reflect.TypeOf(v); t != nil {
switch {
case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func:
isErrField = true
}
}
if isErrField {
tmp := fmt.Sprintf("can not add field %q", k)
if fieldErr != "" {
fieldErr = entry.err + ", " + tmp
} else {
fieldErr = tmp
}
} else {
data[k] = v
}
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
}
// Overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry {
dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context}
}
// getPackageName reduces a fully qualified function name to the package name
// There really ought to be to be a better way...
func getPackageName(f string) string {
for {
lastPeriod := strings.LastIndex(f, ".")
lastSlash := strings.LastIndex(f, "/")
if lastPeriod > lastSlash {
f = f[:lastPeriod]
} else {
break
}
}
return f
}
// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
// dynamic get the package name and the minimum caller depth
for i := 0; i < maximumCallerDepth; i++ {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "getCaller") {
logrusPackage = getPackageName(funcName)
break
}
}
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
// If the caller isn't part of this package, we're done
if pkg != logrusPackage && (f.File[len(f.File)-15:] != "logger_proxy.go") { //sanek
return &f //nolint:scopelint
}
}
// if we got here, we failed to find the caller's context
return nil
}
func (entry Entry) HasCaller() (has bool) {
return entry.Logger != nil &&
entry.Logger.ReportCaller &&
entry.Caller != nil
}
func (entry *Entry) log(level Level, msg string) {
var buffer *bytes.Buffer
newEntry := entry.Dup()
if newEntry.Time.IsZero() {
newEntry.Time = time.Now()
}
newEntry.Level = level
newEntry.Message = msg
newEntry.Logger.mu.Lock()
reportCaller := newEntry.Logger.ReportCaller
bufPool := newEntry.getBufferPool()
newEntry.Logger.mu.Unlock()
if reportCaller {
newEntry.Caller = getCaller()
}
newEntry.fireHooks()
buffer = bufPool.Get()
defer func() {
newEntry.Buffer = nil
buffer.Reset()
bufPool.Put(buffer)
}()
buffer.Reset()
newEntry.Buffer = buffer
newEntry.write()
newEntry.Buffer = nil
// To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here.
if level <= PanicLevel {
panic(entry) //sanek
panic(newEntry)
}
}
func (entry *Entry) getBufferPool() (pool BufferPool) {
if entry.Logger.BufferPool != nil {
return entry.Logger.BufferPool
}
return bufferPool
}
func (entry *Entry) fireHooks() {
var tmpHooks LevelHooks
entry.Logger.mu.Lock()
tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
for k, v := range entry.Logger.Hooks {
tmpHooks[k] = v
}
entry.Logger.mu.Unlock()
err := tmpHooks.Fire(entry.Level, entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
}
}
func (entry *Entry) write() {
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
serialized, err := entry.Logger.Formatter.Format(entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
return
}
if _, err := entry.Logger.Out.Write(serialized); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
}
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Entry.Panic or Entry.Fatal should be used instead.
func (entry *Entry) Log(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}
func (entry *Entry) Trace(args ...interface{}) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...interface{}) {
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...interface{}) {
entry.Info(args...)
}
func (entry *Entry) Info(args ...interface{}) {
entry.Log(InfoLevel, args...)
}
func (entry *Entry) Warn(args ...interface{}) {
entry.Log(WarnLevel, args...)
}
func (entry *Entry) Warning(args ...interface{}) {
entry.Warn(args...)
}
func (entry *Entry) Error(args ...interface{}) {
entry.Log(ErrorLevel, args...)
}
func (entry *Entry) Fatal(args ...interface{}) {
entry.Log(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panic(args ...interface{}) {
entry.Log(PanicLevel, args...)
}
// Entry Printf family functions
func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Tracef(format string, args ...interface{}) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...interface{}) {
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...interface{}) {
entry.Logf(InfoLevel, format, args...)
}
func (entry *Entry) Printf(format string, args ...interface{}) {
entry.Infof(format, args...)
}
func (entry *Entry) Warnf(format string, args ...interface{}) {
entry.Logf(WarnLevel, format, args...)
}
func (entry *Entry) Warningf(format string, args ...interface{}) {
entry.Warnf(format, args...)
}
func (entry *Entry) Errorf(format string, args ...interface{}) {
entry.Logf(ErrorLevel, format, args...)
}
func (entry *Entry) Fatalf(format string, args ...interface{}) {
entry.Logf(FatalLevel, format, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
entry.Logf(PanicLevel, format, args...)
}
// Entry Println family functions
func (entry *Entry) Logln(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, entry.sprintlnn(args...))
}
}
func (entry *Entry) Traceln(args ...interface{}) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...interface{}) {
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...interface{}) {
entry.Logln(InfoLevel, args...)
}
func (entry *Entry) Println(args ...interface{}) {
entry.Infoln(args...)
}
func (entry *Entry) Warnln(args ...interface{}) {
entry.Logln(WarnLevel, args...)
}
func (entry *Entry) Warningln(args ...interface{}) {
entry.Warnln(args...)
}
func (entry *Entry) Errorln(args ...interface{}) {
entry.Logln(ErrorLevel, args...)
}
func (entry *Entry) Fatalln(args ...interface{}) {
entry.Logln(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
entry.Logln(PanicLevel, args...)
}
// Sprintlnn => Sprint no newline. This is to get the behavior of how
// fmt.Sprintln where spaces are always added between operands, regardless of
// their type. Instead of vendoring the Sprintln implementation to spare a
// string allocation, we do the simplest thing.
func (entry *Entry) sprintlnn(args ...interface{}) string {
msg := fmt.Sprintln(args...)
return msg[:len(msg)-1]
}

270
vendor/github.com/ManyakRus/logrus/exported.go generated vendored Normal file
View File

@ -0,0 +1,270 @@
package logrus
import (
"context"
"io"
"time"
)
var (
// std is the name of the standard logger in stdlib `log`
std = New()
)
func StandardLogger() *Logger {
return std
}
// SetOutput sets the standard logger output.
func SetOutput(out io.Writer) {
std.SetOutput(out)
}
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter Formatter) {
std.SetFormatter(formatter)
}
// SetReportCaller sets whether the standard logger will include the calling
// method as a field.
func SetReportCaller(include bool) {
std.SetReportCaller(include)
}
// SetLevel sets the standard logger level.
func SetLevel(level Level) {
std.SetLevel(level)
}
// GetLevel returns the standard logger level.
func GetLevel() Level {
return std.GetLevel()
}
// IsLevelEnabled checks if the log level of the standard logger is greater than the level param
func IsLevelEnabled(level Level) bool {
return std.IsLevelEnabled(level)
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook Hook) {
std.AddHook(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithError(err error) *Entry {
return std.WithField(ErrorKey, err)
}
// WithContext creates an entry from the standard logger and adds a context to it.
func WithContext(ctx context.Context) *Entry {
return std.WithContext(ctx)
}
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithField(key string, value interface{}) *Entry {
return std.WithField(key, value)
}
// WithFields creates an entry from the standard logger and adds multiple
// fields to it. This is simply a helper for `WithField`, invoking it
// once for each field.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithFields(fields Fields) *Entry {
return std.WithFields(fields)
}
// WithTime creates an entry from the standard logger and overrides the time of
// logs generated with it.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithTime(t time.Time) *Entry {
return std.WithTime(t)
}
// Trace logs a message at level Trace on the standard logger.
func Trace(args ...interface{}) {
std.Trace(args...)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
std.Debug(args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...interface{}) {
std.Print(args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
std.Info(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
std.Warn(args...)
}
// Warning logs a message at level Warn on the standard logger.
func Warning(args ...interface{}) {
std.Warning(args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
std.Error(args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...interface{}) {
std.Panic(args...)
}
// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatal(args ...interface{}) {
std.Fatal(args...)
}
// TraceFn logs a message from a func at level Trace on the standard logger.
func TraceFn(fn LogFunction) {
std.TraceFn(fn)
}
// DebugFn logs a message from a func at level Debug on the standard logger.
func DebugFn(fn LogFunction) {
std.DebugFn(fn)
}
// PrintFn logs a message from a func at level Info on the standard logger.
func PrintFn(fn LogFunction) {
std.PrintFn(fn)
}
// InfoFn logs a message from a func at level Info on the standard logger.
func InfoFn(fn LogFunction) {
std.InfoFn(fn)
}
// WarnFn logs a message from a func at level Warn on the standard logger.
func WarnFn(fn LogFunction) {
std.WarnFn(fn)
}
// WarningFn logs a message from a func at level Warn on the standard logger.
func WarningFn(fn LogFunction) {
std.WarningFn(fn)
}
// ErrorFn logs a message from a func at level Error on the standard logger.
func ErrorFn(fn LogFunction) {
std.ErrorFn(fn)
}
// PanicFn logs a message from a func at level Panic on the standard logger.
func PanicFn(fn LogFunction) {
std.PanicFn(fn)
}
// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
func FatalFn(fn LogFunction) {
std.FatalFn(fn)
}
// Tracef logs a message at level Trace on the standard logger.
func Tracef(format string, args ...interface{}) {
std.Tracef(format, args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
std.Debugf(format, args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...interface{}) {
std.Printf(format, args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
std.Infof(format, args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
std.Warnf(format, args...)
}
// Warningf logs a message at level Warn on the standard logger.
func Warningf(format string, args ...interface{}) {
std.Warningf(format, args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
std.Errorf(format, args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...interface{}) {
std.Panicf(format, args...)
}
// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalf(format string, args ...interface{}) {
std.Fatalf(format, args...)
}
// Traceln logs a message at level Trace on the standard logger.
func Traceln(args ...interface{}) {
std.Traceln(args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
std.Debugln(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...interface{}) {
std.Println(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
std.Infoln(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
std.Warnln(args...)
}
// Warningln logs a message at level Warn on the standard logger.
func Warningln(args ...interface{}) {
std.Warningln(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
std.Errorln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...interface{}) {
std.Panicln(args...)
}
// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalln(args ...interface{}) {
std.Fatalln(args...)
}

78
vendor/github.com/ManyakRus/logrus/formatter.go generated vendored Normal file
View File

@ -0,0 +1,78 @@
package logrus
import "time"
// Default key names for the default fields
const (
defaultTimestampFormat = time.RFC3339
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
FieldKeyLogrusError = "logrus_error"
FieldKeyFunc = "func"
FieldKeyFile = "file"
)
// The Formatter interface is used to implement a custom Formatter. It takes an
// `Entry`. It exposes all the fields, including the default ones:
//
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
// * `entry.Data["time"]`. The timestamp.
// * `entry.Data["level"]. The level the entry was logged at.
//
// Any additional fields added with `WithField` or `WithFields` are also in
// `entry.Data`. Format is expected to return an array of bytes which are then
// logged to `logger.Out`.
type Formatter interface {
Format(*Entry) ([]byte, error)
}
// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
// dumping it. If this code wasn't there doing:
//
// logrus.WithField("level", 1).Info("hello")
//
// Would just silently drop the user provided level. Instead with this code
// it'll logged as:
//
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
//
// It's not exported because it's still using Data in an opinionated way. It's to
// avoid code duplication between the two default formatters.
func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) {
timeKey := fieldMap.resolve(FieldKeyTime)
if t, ok := data[timeKey]; ok {
data["fields."+timeKey] = t
delete(data, timeKey)
}
msgKey := fieldMap.resolve(FieldKeyMsg)
if m, ok := data[msgKey]; ok {
data["fields."+msgKey] = m
delete(data, msgKey)
}
levelKey := fieldMap.resolve(FieldKeyLevel)
if l, ok := data[levelKey]; ok {
data["fields."+levelKey] = l
delete(data, levelKey)
}
logrusErrKey := fieldMap.resolve(FieldKeyLogrusError)
if l, ok := data[logrusErrKey]; ok {
data["fields."+logrusErrKey] = l
delete(data, logrusErrKey)
}
// If reportCaller is not set, 'func' will not conflict.
if reportCaller {
funcKey := fieldMap.resolve(FieldKeyFunc)
if l, ok := data[funcKey]; ok {
data["fields."+funcKey] = l
}
fileKey := fieldMap.resolve(FieldKeyFile)
if l, ok := data[fileKey]; ok {
data["fields."+fileKey] = l
}
}
}

34
vendor/github.com/ManyakRus/logrus/hooks.go generated vendored Normal file
View File

@ -0,0 +1,34 @@
package logrus
// A hook to be fired when logging on the logging levels returned from
// `Levels()` on your implementation of the interface. Note that this is not
// fired in a goroutine or a channel with workers, you should handle such
// functionality yourself if your call is non-blocking and you don't wish for
// the logging calls for levels returned from `Levels()` to block.
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
// Internal type for storing the hooks on a logger instance.
type LevelHooks map[Level][]Hook
// Add a hook to an instance of logger. This is called with
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
func (hooks LevelHooks) Add(hook Hook) {
for _, level := range hook.Levels() {
hooks[level] = append(hooks[level], hook)
}
}
// Fire all the hooks for the passed level. Used by `entry.log` to fire
// appropriate hooks for a log entry.
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
for _, hook := range hooks[level] {
if err := hook.Fire(entry); err != nil {
return err
}
}
return nil
}

128
vendor/github.com/ManyakRus/logrus/json_formatter.go generated vendored Normal file
View File

@ -0,0 +1,128 @@
package logrus
import (
"bytes"
"encoding/json"
"fmt"
"runtime"
)
type fieldKey string
// FieldMap allows customization of the key names for default fields.
type FieldMap map[fieldKey]string
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
// JSONFormatter formats logs into parsable json
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
// The format to use is the same than for time.Format or time.Parse from the standard
// library.
// The standard Library already provides a set of predefined format.
TimestampFormat string
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
// DisableHTMLEscape allows disabling html escaping in output
DisableHTMLEscape bool
// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
DataKey string
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message",
// FieldKeyFunc: "@caller",
// },
// }
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the json data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from json fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
// PrettyPrint will indent all json logs
PrettyPrint bool
}
// Format renders a single log entry
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+4)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
if f.DataKey != "" {
newData := make(Fields, 4)
newData[f.DataKey] = data
data = newData
}
prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if entry.err != "" {
data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err
}
if !f.DisableTimestamp {
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
}
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
if entry.HasCaller() {
funcVal := entry.Caller.Function
fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
}
if funcVal != "" {
data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal
}
if fileVal != "" {
data[f.FieldMap.resolve(FieldKeyFile)] = fileVal
}
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
encoder := json.NewEncoder(b)
encoder.SetEscapeHTML(!f.DisableHTMLEscape)
if f.PrettyPrint {
encoder.SetIndent("", " ")
}
if err := encoder.Encode(data); err != nil {
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
}
return b.Bytes(), nil
}

417
vendor/github.com/ManyakRus/logrus/logger.go generated vendored Normal file
View File

@ -0,0 +1,417 @@
package logrus
import (
"context"
"io"
"os"
"sync"
"sync/atomic"
"time"
)
// LogFunction For big messages, it can be more efficient to pass a function
// and only call it if the log level is actually enables rather than
// generating the log message and then checking if the level is enabled
type LogFunction func() []interface{}
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventurous, such as logging to Kafka.
Out io.Writer
// Hooks for the logger instance. These allow firing events based on logging
// levels and log entries. For example, to send errors to an error tracking
// service, log to StatsD or dump the core on fatal errors.
Hooks LevelHooks
// All log entries pass through the formatter before logged to Out. The
// included formatters are `TextFormatter` and `JSONFormatter` for which
// TextFormatter is the default. In development (when a TTY is attached) it
// logs with colors, but to a file it wouldn't. You can easily implement your
// own that implements the `Formatter` interface, see the `README` or included
// formatters for examples.
Formatter Formatter
// Flag for whether to log caller info (off by default)
ReportCaller bool
// The logging level the logger should log at. This is typically (and defaults
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
// logged.
Level Level
// Used to sync writing to the log. Locking is enabled by Default
mu MutexWrap
// Reusable empty entry
entryPool sync.Pool
// Function to exit the application, defaults to `os.Exit()`
ExitFunc exitFunc
// The buffer pool used to format the log. If it is nil, the default global
// buffer pool will be used.
BufferPool BufferPool
}
type exitFunc func(int)
type MutexWrap struct {
lock sync.Mutex
disabled bool
}
func (mw *MutexWrap) Lock() {
if !mw.disabled {
mw.lock.Lock()
}
}
func (mw *MutexWrap) Unlock() {
if !mw.disabled {
mw.lock.Unlock()
}
}
func (mw *MutexWrap) Disable() {
mw.disabled = true
}
// Creates a new logger. Configuration should be set by changing `Formatter`,
// `Out` and `Hooks` directly on the default logger instance. You can also just
// instantiate your own:
//
// var log = &logrus.Logger{
// Out: os.Stderr,
// Formatter: new(logrus.TextFormatter),
// Hooks: make(logrus.LevelHooks),
// Level: logrus.DebugLevel,
// }
//
// It's recommended to make this a global instance called `log`.
func New() *Logger {
return &Logger{
Out: os.Stderr,
Formatter: new(TextFormatter),
Hooks: make(LevelHooks),
Level: InfoLevel,
ExitFunc: os.Exit,
ReportCaller: false,
}
}
func (logger *Logger) newEntry() *Entry {
entry, ok := logger.entryPool.Get().(*Entry)
if ok {
return entry
}
return NewEntry(logger)
}
func (logger *Logger) releaseEntry(entry *Entry) {
entry.Data = map[string]interface{}{}
logger.entryPool.Put(entry)
}
// WithField allocates a new entry and adds a field to it.
// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func (logger *Logger) WithField(key string, value interface{}) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func (logger *Logger) WithFields(fields Fields) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func (logger *Logger) WithError(err error) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithError(err)
}
// Add a context to the log entry.
func (logger *Logger) WithContext(ctx context.Context) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithContext(ctx)
}
// Overrides the time of the log entry.
func (logger *Logger) WithTime(t time.Time) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithTime(t)
}
func (logger *Logger) Logf(level Level, format string, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logf(level, format, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Tracef(format string, args ...interface{}) {
logger.Logf(TraceLevel, format, args...)
}
func (logger *Logger) Debugf(format string, args ...interface{}) {
logger.Logf(DebugLevel, format, args...)
}
func (logger *Logger) Infof(format string, args ...interface{}) {
logger.Logf(InfoLevel, format, args...)
}
func (logger *Logger) Printf(format string, args ...interface{}) {
entry := logger.newEntry()
entry.Printf(format, args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnf(format string, args ...interface{}) {
logger.Logf(WarnLevel, format, args...)
}
func (logger *Logger) Warningf(format string, args ...interface{}) {
logger.Warnf(format, args...)
}
func (logger *Logger) Errorf(format string, args ...interface{}) {
logger.Logf(ErrorLevel, format, args...)
}
func (logger *Logger) Fatalf(format string, args ...interface{}) {
logger.Logf(FatalLevel, format, args...)
logger.Exit(1)
}
func (logger *Logger) Panicf(format string, args ...interface{}) {
logger.Logf(PanicLevel, format, args...)
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Logger.Panic or Logger.Fatal should be used instead.
func (logger *Logger) Log(level Level, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) LogFn(level Level, fn LogFunction) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, fn()...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Trace(args ...interface{}) {
logger.Log(TraceLevel, args...)
}
func (logger *Logger) Debug(args ...interface{}) {
logger.Log(DebugLevel, args...)
}
func (logger *Logger) Info(args ...interface{}) {
logger.Log(InfoLevel, args...)
}
func (logger *Logger) Print(args ...interface{}) {
entry := logger.newEntry()
entry.Print(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warn(args ...interface{}) {
logger.Log(WarnLevel, args...)
}
func (logger *Logger) Warning(args ...interface{}) {
logger.Warn(args...)
}
func (logger *Logger) Error(args ...interface{}) {
logger.Log(ErrorLevel, args...)
}
func (logger *Logger) Fatal(args ...interface{}) {
logger.Log(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panic(args ...interface{}) {
logger.Log(PanicLevel, args...)
}
func (logger *Logger) TraceFn(fn LogFunction) {
logger.LogFn(TraceLevel, fn)
}
func (logger *Logger) DebugFn(fn LogFunction) {
logger.LogFn(DebugLevel, fn)
}
func (logger *Logger) InfoFn(fn LogFunction) {
logger.LogFn(InfoLevel, fn)
}
func (logger *Logger) PrintFn(fn LogFunction) {
entry := logger.newEntry()
entry.Print(fn()...)
logger.releaseEntry(entry)
}
func (logger *Logger) WarnFn(fn LogFunction) {
logger.LogFn(WarnLevel, fn)
}
func (logger *Logger) WarningFn(fn LogFunction) {
logger.WarnFn(fn)
}
func (logger *Logger) ErrorFn(fn LogFunction) {
logger.LogFn(ErrorLevel, fn)
}
func (logger *Logger) FatalFn(fn LogFunction) {
logger.LogFn(FatalLevel, fn)
logger.Exit(1)
}
func (logger *Logger) PanicFn(fn LogFunction) {
logger.LogFn(PanicLevel, fn)
}
func (logger *Logger) Logln(level Level, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logln(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Traceln(args ...interface{}) {
logger.Logln(TraceLevel, args...)
}
func (logger *Logger) Debugln(args ...interface{}) {
logger.Logln(DebugLevel, args...)
}
func (logger *Logger) Infoln(args ...interface{}) {
logger.Logln(InfoLevel, args...)
}
func (logger *Logger) Println(args ...interface{}) {
entry := logger.newEntry()
entry.Println(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnln(args ...interface{}) {
logger.Logln(WarnLevel, args...)
}
func (logger *Logger) Warningln(args ...interface{}) {
logger.Warnln(args...)
}
func (logger *Logger) Errorln(args ...interface{}) {
logger.Logln(ErrorLevel, args...)
}
func (logger *Logger) Fatalln(args ...interface{}) {
logger.Logln(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panicln(args ...interface{}) {
logger.Logln(PanicLevel, args...)
}
func (logger *Logger) Exit(code int) {
runHandlers()
if logger.ExitFunc == nil {
logger.ExitFunc = os.Exit
}
logger.ExitFunc(code)
}
// When file is opened with appending mode, it's safe to
// write concurrently to a file (within 4k message on Linux).
// In these cases user can choose to disable the lock.
func (logger *Logger) SetNoLock() {
logger.mu.Disable()
}
func (logger *Logger) level() Level {
return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
}
// SetLevel sets the logger level.
func (logger *Logger) SetLevel(level Level) {
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
}
// GetLevel returns the logger level.
func (logger *Logger) GetLevel() Level {
return logger.level()
}
// AddHook adds a hook to the logger hooks.
func (logger *Logger) AddHook(hook Hook) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Hooks.Add(hook)
}
// IsLevelEnabled checks if the log level of the logger is greater than the level param
func (logger *Logger) IsLevelEnabled(level Level) bool {
return logger.level() >= level
}
// SetFormatter sets the logger formatter.
func (logger *Logger) SetFormatter(formatter Formatter) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Formatter = formatter
}
// SetOutput sets the logger output.
func (logger *Logger) SetOutput(output io.Writer) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Out = output
}
func (logger *Logger) SetReportCaller(reportCaller bool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.ReportCaller = reportCaller
}
// ReplaceHooks replaces the logger hooks and returns the old ones
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
logger.mu.Lock()
oldHooks := logger.Hooks
logger.Hooks = hooks
logger.mu.Unlock()
return oldHooks
}
// SetBufferPool sets the logger buffer pool.
func (logger *Logger) SetBufferPool(pool BufferPool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.BufferPool = pool
}

186
vendor/github.com/ManyakRus/logrus/logrus.go generated vendored Normal file
View File

@ -0,0 +1,186 @@
package logrus
import (
"fmt"
"log"
"strings"
)
// Fields type, used to pass to `WithFields`.
type Fields map[string]interface{}
// Level type
type Level uint32
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
func (level Level) String() string {
if b, err := level.MarshalText(); err == nil {
return string(b)
} else {
return "unknown"
}
}
// ParseLevel takes a string level and returns the Logrus log level constant.
func ParseLevel(lvl string) (Level, error) {
switch strings.ToLower(lvl) {
case "panic":
return PanicLevel, nil
case "fatal":
return FatalLevel, nil
case "error":
return ErrorLevel, nil
case "warn", "warning":
return WarnLevel, nil
case "info":
return InfoLevel, nil
case "debug":
return DebugLevel, nil
case "trace":
return TraceLevel, nil
}
var l Level
return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (level *Level) UnmarshalText(text []byte) error {
l, err := ParseLevel(string(text))
if err != nil {
return err
}
*level = l
return nil
}
func (level Level) MarshalText() ([]byte, error) {
switch level {
case TraceLevel:
return []byte("trace"), nil
case DebugLevel:
return []byte("debug"), nil
case InfoLevel:
return []byte("info"), nil
case WarnLevel:
return []byte("warning"), nil
case ErrorLevel:
return []byte("error"), nil
case FatalLevel:
return []byte("fatal"), nil
case PanicLevel:
return []byte("panic"), nil
}
return nil, fmt.Errorf("not a valid logrus level %d", level)
}
// A constant exposing all logging levels
var AllLevels = []Level{
PanicLevel,
FatalLevel,
ErrorLevel,
WarnLevel,
InfoLevel,
DebugLevel,
TraceLevel,
}
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
// Won't compile if StdLogger can't be realized by a log.Logger
var (
_ StdLogger = &log.Logger{}
_ StdLogger = &Entry{}
_ StdLogger = &Logger{}
)
// StdLogger is what your logrus-enabled library should take, that way
// it'll accept a stdlib logger and a logrus logger. There's no standard
// interface, this is the closest we get, unfortunately.
type StdLogger interface {
Print(...interface{})
Printf(string, ...interface{})
Println(...interface{})
Fatal(...interface{})
Fatalf(string, ...interface{})
Fatalln(...interface{})
Panic(...interface{})
Panicf(string, ...interface{})
Panicln(...interface{})
}
// The FieldLogger interface generalizes the Entry and Logger types
type FieldLogger interface {
WithField(key string, value interface{}) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Printf(format string, args ...interface{})
Warnf(format string, args ...interface{})
Warningf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
Debug(args ...interface{})
Info(args ...interface{})
Print(args ...interface{})
Warn(args ...interface{})
Warning(args ...interface{})
Error(args ...interface{})
Fatal(args ...interface{})
Panic(args ...interface{})
Debugln(args ...interface{})
Infoln(args ...interface{})
Println(args ...interface{})
Warnln(args ...interface{})
Warningln(args ...interface{})
Errorln(args ...interface{})
Fatalln(args ...interface{})
Panicln(args ...interface{})
// IsDebugEnabled() bool
// IsInfoEnabled() bool
// IsWarnEnabled() bool
// IsErrorEnabled() bool
// IsFatalEnabled() bool
// IsPanicEnabled() bool
}
// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is
// here for consistancy. Do not use. Use Logger or Entry instead.
type Ext1FieldLogger interface {
FieldLogger
Tracef(format string, args ...interface{})
Trace(args ...interface{})
Traceln(args ...interface{})
}

View File

@ -0,0 +1,11 @@
// +build appengine
package logrus
import (
"io"
)
func checkIfTerminal(w io.Writer) bool {
return true
}

View File

@ -0,0 +1,13 @@
// +build darwin dragonfly freebsd netbsd openbsd
// +build !js
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TIOCGETA
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}

View File

@ -0,0 +1,7 @@
// +build js
package logrus
func isTerminal(fd int) bool {
return false
}

View File

@ -0,0 +1,11 @@
// +build js nacl plan9
package logrus
import (
"io"
)
func checkIfTerminal(w io.Writer) bool {
return false
}

View File

@ -0,0 +1,17 @@
// +build !appengine,!js,!windows,!nacl,!plan9
package logrus
import (
"io"
"os"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
return isTerminal(int(v.Fd()))
default:
return false
}
}

View File

@ -0,0 +1,11 @@
package logrus
import (
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermio(fd, unix.TCGETA)
return err == nil
}

View File

@ -0,0 +1,13 @@
// +build linux aix zos
// +build !js
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TCGETS
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}

View File

@ -0,0 +1,27 @@
// +build !appengine,!js,windows
package logrus
import (
"io"
"os"
"golang.org/x/sys/windows"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
handle := windows.Handle(v.Fd())
var mode uint32
if err := windows.GetConsoleMode(handle, &mode); err != nil {
return false
}
mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
if err := windows.SetConsoleMode(handle, mode); err != nil {
return false
}
return true
}
return false
}

339
vendor/github.com/ManyakRus/logrus/text_formatter.go generated vendored Normal file
View File

@ -0,0 +1,339 @@
package logrus
import (
"bytes"
"fmt"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
const (
red = 31
yellow = 33
blue = 36
gray = 37
)
var baseTimestamp time.Time
func init() {
baseTimestamp = time.Now()
}
// TextFormatter formats logs into text
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
// Force disabling colors.
DisableColors bool
// Force quoting of all values
ForceQuote bool
// DisableQuote disables quoting for all values.
// DisableQuote will have a lower priority than ForceQuote.
// If both of them are set to true, quote will be forced on all values.
DisableQuote bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
EnvironmentOverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool
// TimestampFormat to use for display when a full timestamp is printed.
// The format to use is the same than for time.Format or time.Parse from the standard
// library.
// The standard Library already provides a set of predefined format.
TimestampFormat string
// The fields are sorted by default for a consistent output. For applications
// that log extremely frequently and don't use the JSON formatter this may not
// be desired.
DisableSorting bool
// The keys sorting function, when uninitialized it uses sort.Strings.
SortingFunc func([]string)
// Disables the truncation of the level text to 4 characters.
DisableLevelTruncation bool
// PadLevelText Adds padding the level text so that all the levels output at the same length
// PadLevelText is a superset of the DisableLevelTruncation option
PadLevelText bool
// QuoteEmptyFields will wrap empty fields in quotes if true
QuoteEmptyFields bool
// Whether the logger's out is to a terminal
isTerminal bool
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &TextFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message"}}
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
terminalInitOnce sync.Once
// The max length of the level text, generated dynamically on init
levelTextMaxLength int
}
func (f *TextFormatter) init(entry *Entry) {
if entry.Logger != nil {
f.isTerminal = checkIfTerminal(entry.Logger.Out)
}
// Get the max length of the level text
for _, level := range AllLevels {
levelTextLength := utf8.RuneCount([]byte(level.String()))
if levelTextLength > f.levelTextMaxLength {
f.levelTextMaxLength = levelTextLength
}
}
}
func (f *TextFormatter) isColored() bool {
isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows"))
if f.EnvironmentOverrideColors {
switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); {
case ok && force != "0":
isColored = true
case ok && force == "0", os.Getenv("CLICOLOR") == "0":
isColored = false
}
}
return isColored && !f.DisableColors
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields)
for k, v := range entry.Data {
data[k] = v
}
prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
var funcVal, fileVal string
fixedKeys := make([]string, 0, 4+len(data))
if !f.DisableTimestamp {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
}
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
if entry.Message != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
}
if entry.err != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
}
if entry.HasCaller() {
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
} else {
funcVal = entry.Caller.Function
fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
}
if funcVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
}
if fileVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
}
}
if !f.DisableSorting {
if f.SortingFunc == nil {
sort.Strings(keys)
fixedKeys = append(fixedKeys, keys...)
} else {
if !f.isColored() {
fixedKeys = append(fixedKeys, keys...)
f.SortingFunc(fixedKeys)
} else {
f.SortingFunc(keys)
}
}
} else {
fixedKeys = append(fixedKeys, keys...)
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
f.terminalInitOnce.Do(func() { f.init(entry) })
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if f.isColored() {
f.printColored(b, entry, keys, data, timestampFormat)
} else {
for _, key := range fixedKeys {
var value interface{}
switch {
case key == f.FieldMap.resolve(FieldKeyTime):
value = entry.Time.Format(timestampFormat)
case key == f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String()
case key == f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message
case key == f.FieldMap.resolve(FieldKeyLogrusError):
value = entry.err
case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
value = funcVal
case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
value = fileVal
default:
value = data[key]
}
f.appendKeyValue(b, key, value)
}
}
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) {
var levelColor int
switch entry.Level {
case DebugLevel, TraceLevel:
levelColor = gray
case WarnLevel:
levelColor = yellow
case ErrorLevel, FatalLevel, PanicLevel:
levelColor = red
case InfoLevel:
levelColor = blue
default:
levelColor = blue
}
levelText := strings.ToUpper(entry.Level.String())
if !f.DisableLevelTruncation && !f.PadLevelText {
levelText = levelText[0:4]
}
if f.PadLevelText {
// Generates the format string used in the next line, for example "%-6s" or "%-7s".
// Based on the max level text length.
formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s"
// Formats the level text by appending spaces up to the max length, for example:
// - "INFO "
// - "WARNING"
levelText = fmt.Sprintf(formatString, levelText)
}
// Remove a single newline if it already exists in the message to keep
// the behavior of logrus text_formatter the same as the stdlib log package
entry.Message = strings.TrimSuffix(entry.Message, "\n")
caller := ""
if entry.HasCaller() {
funcVal := fmt.Sprintf("%s()", entry.Caller.Function)
fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
}
if fileVal == "" {
caller = funcVal
} else if funcVal == "" {
caller = fileVal
} else {
caller = fileVal + " " + funcVal
}
}
switch {
case f.DisableTimestamp:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message)
case !f.FullTimestamp:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
default:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
}
for _, k := range keys {
v := data[k]
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
f.appendValue(b, v)
}
}
func (f *TextFormatter) needsQuoting(text string) bool {
if f.ForceQuote {
return true
}
if f.QuoteEmptyFields && len(text) == 0 {
return true
}
if f.DisableQuote {
return false
}
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
return true
}
}
return false
}
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(key)
b.WriteByte('=')
f.appendValue(b, value)
}
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}

70
vendor/github.com/ManyakRus/logrus/writer.go generated vendored Normal file
View File

@ -0,0 +1,70 @@
package logrus
import (
"bufio"
"io"
"runtime"
)
// Writer at INFO level. See WriterLevel for details.
func (logger *Logger) Writer() *io.PipeWriter {
return logger.WriterLevel(InfoLevel)
}
// WriterLevel returns an io.Writer that can be used to write arbitrary text to
// the logger at the given log level. Each line written to the writer will be
// printed in the usual way using formatters and hooks. The writer is part of an
// io.Pipe and it is the callers responsibility to close the writer when done.
// This can be used to override the standard library logger easily.
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
return NewEntry(logger).WriterLevel(level)
}
func (entry *Entry) Writer() *io.PipeWriter {
return entry.WriterLevel(InfoLevel)
}
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
reader, writer := io.Pipe()
var printFunc func(args ...interface{})
switch level {
case TraceLevel:
printFunc = entry.Trace
case DebugLevel:
printFunc = entry.Debug
case InfoLevel:
printFunc = entry.Info
case WarnLevel:
printFunc = entry.Warn
case ErrorLevel:
printFunc = entry.Error
case FatalLevel:
printFunc = entry.Fatal
case PanicLevel:
printFunc = entry.Panic
default:
printFunc = entry.Print
}
go entry.writerScanner(reader, printFunc)
runtime.SetFinalizer(writer, writerFinalizer)
return writer
}
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
printFunc(scanner.Text())
}
if err := scanner.Err(); err != nil {
entry.Errorf("Error while reading from Writer: %s", err)
}
reader.Close()
}
func writerFinalizer(writer *io.PipeWriter) {
writer.Close()
}

42
vendor/github.com/ManyakRus/starter/config/config.go generated vendored Normal file
View File

@ -0,0 +1,42 @@
// модуль для загрузки переменных окружения в структуру
package config
import (
"github.com/joho/godotenv"
"github.com/ManyakRus/starter/logger"
"github.com/ManyakRus/starter/micro"
//log "github.com/sirupsen/logrus"
//log "github.com/sirupsen/logrus"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/types"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/micro"
)
// log хранит используемый логгер
var log = logger.GetLog()
// LoadEnv - загружает переменные окружения в структуру из файла или из переменных окружения
func LoadEnv() {
dir := micro.ProgramDir()
filename := dir + ".env"
LoadEnv_from_file(filename)
}
// LoadEnv_from_file загружает переменные окружения в структуру из файла или из переменных окружения
func LoadEnv_from_file(filename string) {
err := godotenv.Load(filename)
if err != nil {
log.Debug("Can not parse .env file: ", filename, " warning: "+err.Error())
} else {
log.Info("load .env from file: ", filename)
}
//LOG_LEVEL := os.Getenv("LOG_LEVEL")
//if LOG_LEVEL == "" {
// LOG_LEVEL = "info"
//}
//logger.SetLevel(LOG_LEVEL)
}

View File

@ -0,0 +1,52 @@
// модуль для получения единого Context приложения
package contextmain
import (
"context"
"sync"
)
// Ctx хранит глобальный контекст программы
// не использовать
// * - чтоб можно было засунуть ссылку на чужой контекст
var Ctx *context.Context
// CancelContext - функция отмены глобального контекста
var CancelContext func()
// onceCtx - гарантирует единственное создание контеста
var onceCtx sync.Once
// lockContextMain - гарантирует единственное создание контеста
// var lockContextMain sync.Mutex
// GetContext - возвращает глобальный контекст приложения
func GetContext() context.Context {
//lockContextMain.Lock()
//defer lockContextMain.Unlock()
//
//if Ctx == nil {
// CtxBg := context.Background()
// Ctx, CancelContext = context.WithCancel(CtxBg)
//}
onceCtx.Do(func() {
CtxBg := context.Background()
var Ctx0 context.Context
Ctx0, CancelContext = context.WithCancel(CtxBg)
Ctx = &Ctx0
})
return *Ctx
}
// GetNewContext - создаёт и возвращает новый контекст приложения
func GetNewContext() context.Context {
CtxBg := context.Background()
var Ctx0 context.Context
Ctx0, CancelContext = context.WithCancel(CtxBg)
Ctx = &Ctx0
return *Ctx
}

22
vendor/github.com/ManyakRus/starter/log/logger.go generated vendored Normal file
View File

@ -0,0 +1,22 @@
// модуль создания единого логирования
package log
import (
"github.com/ManyakRus/starter/logger"
//"github.com/google/logger"
//"github.com/sirupsen/logrus"
logrus "github.com/ManyakRus/logrus"
)
// GetLog - возвращает глобальный логгер приложения
// и создаёт логгер если ещё не создан
func GetLog() *logrus.Logger {
return logger.GetLog()
}
// SetLevel - изменяет уровень логирования
func SetLevel(LOG_LEVEL string) {
logger.SetLevel(LOG_LEVEL)
}

259
vendor/github.com/ManyakRus/starter/log/logger_proxy.go generated vendored Normal file
View File

@ -0,0 +1,259 @@
// дублирует все функции логгера logrus
package log
import (
"context"
"github.com/ManyakRus/logrus"
"github.com/ManyakRus/starter/logger"
"io"
"time"
)
// WithField allocates a new entry and adds a field to it.
// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func WithField(key string, value interface{}) *logrus.Entry {
return logger.GetLog().WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func WithFields(fields logrus.Fields) *logrus.Entry {
return GetLog().WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func WithError(err error) *logrus.Entry {
return GetLog().WithError(err)
}
// Add a context to the log entry.
func WithContext(ctx context.Context) *logrus.Entry {
return GetLog().WithContext(ctx)
}
// Overrides the time of the log entry.
func WithTime(t time.Time) *logrus.Entry {
return GetLog().WithTime(t)
}
func Logf(level logrus.Level, format string, args ...interface{}) {
GetLog().Logf(level, format, args...)
}
func Tracef(format string, args ...interface{}) {
GetLog().Tracef(format, args...)
}
func Debugf(format string, args ...interface{}) {
GetLog().Debugf(format, args...)
}
func Infof(format string, args ...interface{}) {
GetLog().Infof(format, args...)
}
func Printf(format string, args ...interface{}) {
GetLog().Printf(format, args...)
}
func Warnf(format string, args ...interface{}) {
GetLog().Warnf(format, args...)
}
func Warningf(format string, args ...interface{}) {
GetLog().Warningf(format, args...)
}
func Errorf(format string, args ...interface{}) {
GetLog().Errorf(format, args...)
}
func Fatalf(format string, args ...interface{}) {
GetLog().Fatalf(format, args...)
}
func Panicf(format string, args ...interface{}) {
GetLog().Panicf(format, args...)
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Logger.Panic or Logger.Fatal should be used instead.
func Log(level logrus.Level, args ...interface{}) {
GetLog().Log(level, args...)
}
func LogFn(level logrus.Level, fn logrus.LogFunction) {
GetLog().LogFn(level, fn)
}
func Trace(args ...interface{}) {
GetLog().Trace(args...)
}
func Debug(args ...interface{}) {
GetLog().Debug(args...)
}
func Info(args ...interface{}) {
GetLog().Info(args...)
}
func Print(args ...interface{}) {
GetLog().Print(args...)
}
func Warn(args ...interface{}) {
GetLog().Warn(args...)
}
func Warning(args ...interface{}) {
GetLog().Warning(args...)
}
func Error(args ...interface{}) {
GetLog().Error(args...)
}
func Fatal(args ...interface{}) {
GetLog().Fatal(args...)
}
func Panic(args ...interface{}) {
GetLog().Panic(args...)
}
func TraceFn(fn logrus.LogFunction) {
GetLog().TraceFn(fn)
}
func DebugFn(fn logrus.LogFunction) {
GetLog().DebugFn(fn)
}
func InfoFn(fn logrus.LogFunction) {
GetLog().InfoFn(fn)
}
func PrintFn(fn logrus.LogFunction) {
GetLog().PrintFn(fn)
}
func WarnFn(fn logrus.LogFunction) {
GetLog().WarnFn(fn)
}
func WarningFn(fn logrus.LogFunction) {
GetLog().WarningFn(fn)
}
func ErrorFn(fn logrus.LogFunction) {
GetLog().ErrorFn(fn)
}
func FatalFn(fn logrus.LogFunction) {
GetLog().FatalFn(fn)
}
func PanicFn(fn logrus.LogFunction) {
GetLog().PanicFn(fn)
}
func Logln(level logrus.Level, args ...interface{}) {
GetLog().Logln(level, args...)
}
func Traceln(args ...interface{}) {
GetLog().Traceln(args...)
}
func Debugln(args ...interface{}) {
GetLog().Debugln(args...)
}
func Infoln(args ...interface{}) {
GetLog().Infoln(args...)
}
func Println(args ...interface{}) {
GetLog().Println(args...)
}
func Warnln(args ...interface{}) {
GetLog().Warnln(args...)
}
func Warningln(args ...interface{}) {
GetLog().Warningln(args...)
}
func Errorln(args ...interface{}) {
GetLog().Errorln(args...)
}
func Fatalln(args ...interface{}) {
GetLog().Fatalln(args...)
}
func Panicln(args ...interface{}) {
GetLog().Panicln(args...)
}
func Exit(code int) {
GetLog().Exit(code)
}
// When file is opened with appending mode, it's safe to
// write concurrently to a file (within 4k message on Linux).
// In these cases user can choose to disable the lock.
func SetNoLock() {
GetLog().SetNoLock()
}
//// SetLevel sets the logger level.
//func SetLevel(level logrus.Level) {
//}
// GetLevel returns the logger level.
func GetLevel() logrus.Level {
return GetLog().GetLevel()
}
// AddHook adds a hook to the logger hooks.
func AddHook(hook logrus.Hook) {
GetLog().AddHook(hook)
}
// IsLevelEnabled checks if the log level of the logger is greater than the level param
func IsLevelEnabled(level logrus.Level) bool {
return GetLog().IsLevelEnabled(level)
}
// SetFormatter sets the logger formatter.
func SetFormatter(formatter logrus.Formatter) {
GetLog().SetFormatter(formatter)
}
// SetOutput sets the logger output.
func SetOutput(output io.Writer) {
GetLog().SetOutput(output)
}
func SetReportCaller(reportCaller bool) {
GetLog().SetReportCaller(reportCaller)
}
// ReplaceHooks replaces the logger hooks and returns the old ones
func ReplaceHooks(hooks logrus.LevelHooks) logrus.LevelHooks {
GetLog()
return ReplaceHooks(hooks)
}
// SetBufferPool sets the logger buffer pool.
func SetBufferPool(pool logrus.BufferPool) {
GetLog().SetBufferPool(pool)
}

89
vendor/github.com/ManyakRus/starter/logger/logger.go generated vendored Normal file
View File

@ -0,0 +1,89 @@
// модуль создания единого логирования
package logger
import (
"os"
"path"
"runtime"
"strconv"
"sync"
//"github.com/google/logger"
//"github.com/sirupsen/logrus"
logrus "github.com/ManyakRus/logrus"
"github.com/ManyakRus/starter/micro"
)
// log - глобальный логгер приложения
var log *logrus.Logger
// onceLog - гарантирует единственное создание логгера
var onceLog sync.Once
// GetLog - возвращает глобальный логгер приложения
// и создаёт логгер если ещё не создан
func GetLog() *logrus.Logger {
onceLog.Do(func() {
log = logrus.New()
log.SetReportCaller(true)
Formatter := new(logrus.TextFormatter)
Formatter.TimestampFormat = "2006-01-02 15:04:05.000"
Formatter.FullTimestamp = true
Formatter.CallerPrettyfier = CallerPrettyfier
log.SetFormatter(Formatter)
LOG_LEVEL := os.Getenv("LOG_LEVEL")
SetLevel(LOG_LEVEL)
//LOG_FILE := "log.txt"
//file, err := os.OpenFile(LOG_FILE, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
//if err != nil {
// log.Fatal(err)
//}
////defer file.Close()
//
//mw := io.MultiWriter(os.Stderr, file)
//logrus.SetOutput(mw)
//log.SetOutput(os.Stdout)
//log.SetOutput(file)
})
return log
}
// CallerPrettyfier - форматирует имя файла и номер строки кода
func CallerPrettyfier(frame *runtime.Frame) (function string, file string) {
fileName := " " + path.Base(frame.File) + ":" + strconv.Itoa(frame.Line) + "\t"
FunctionName := frame.Function
FunctionName = micro.LastWord(FunctionName)
FunctionName = FunctionName + "()" + "\t"
return FunctionName, fileName
}
// SetLevel - изменяет уровень логирования
func SetLevel(LOG_LEVEL string) {
if log == nil {
GetLog()
}
if LOG_LEVEL == "" {
LOG_LEVEL = "debug"
}
level, err := logrus.ParseLevel(LOG_LEVEL)
if err != nil {
log.Error("logrus.ParseLevel() error: ", err)
}
if level == log.Level {
return
}
log.SetLevel(level)
log.Debug("new level: ", LOG_LEVEL)
}

View File

@ -0,0 +1,311 @@
// дублирует все функции логгера logrus
package logger
//
//import (
// "context"
// "github.com/sirupsen/logrus"
// "io"
// "time"
//)
//
//// WithField allocates a new entry and adds a field to it.
//// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
//// this new returned entry.
//// If you want multiple fields, use `WithFields`.
//func WithField(key string, value interface{}) *logrus.Entry {
// return log.WithField(key, value)
//}
//
//// Adds a struct of fields to the log entry. All it does is call `WithField` for
//// each `Field`.
//func WithFields(fields logrus.Fields) *logrus.Entry {
// GetLog()
// return log.WithFields(fields)
//}
//
//// Add an error as single field to the log entry. All it does is call
//// `WithError` for the given `error`.
//func WithError(err error) *logrus.Entry {
// GetLog()
// return log.WithError(err)
//}
//
//// Add a context to the log entry.
//func WithContext(ctx context.Context) *logrus.Entry {
// GetLog()
// return log.WithContext(ctx)
//}
//
//// Overrides the time of the log entry.
//func WithTime(t time.Time) *logrus.Entry {
// GetLog()
// return WithTime(t)
//}
//
//func Logf(level logrus.Level, format string, args ...interface{}) {
// GetLog()
// log.Logf(level, format, args...)
//}
//
//func Tracef(format string, args ...interface{}) {
// GetLog()
// log.Tracef(format, args...)
//}
//
//func Debugf(format string, args ...interface{}) {
// GetLog()
// log.Debugf(format, args...)
//}
//
//func Infof(format string, args ...interface{}) {
// GetLog()
// log.Infof(format, args...)
//}
//
//func Printf(format string, args ...interface{}) {
// GetLog()
// log.Printf(format, args...)
//}
//
//func Warnf(format string, args ...interface{}) {
// GetLog()
// log.Warnf(format, args...)
//}
//
//func Warningf(format string, args ...interface{}) {
// GetLog()
// log.Warningf(format, args...)
//}
//
//func Errorf(format string, args ...interface{}) {
// GetLog()
// log.Errorf(format, args...)
//}
//
//func Fatalf(format string, args ...interface{}) {
// GetLog()
// log.Fatalf(format, args...)
//}
//
//func Panicf(format string, args ...interface{}) {
// GetLog()
// log.Panicf(format, args...)
//}
//
//// Log will log a message at the level given as parameter.
//// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
//// For this behaviour Logger.Panic or Logger.Fatal should be used instead.
//func Log(level logrus.Level, args ...interface{}) {
// GetLog()
// log.Log(level, args...)
//}
//
//func LogFn(level logrus.Level, fn logrus.LogFunction) {
// GetLog()
// log.LogFn(level, fn)
//}
//
//func Trace(args ...interface{}) {
// GetLog()
// log.Trace(args...)
//}
//
//func Debug(args ...interface{}) {
// GetLog()
// log.Debug(args...)
//}
//
//func Info(args ...interface{}) {
// GetLog()
// log.Info(args...)
//}
//
//func Print(args ...interface{}) {
// GetLog()
// log.Print(args...)
//}
//
//func Warn(args ...interface{}) {
// GetLog()
// log.Warn(args...)
//}
//
//func Warning(args ...interface{}) {
// GetLog()
// log.Warning(args...)
//}
//
//func Error(args ...interface{}) {
// GetLog()
// log.Error(args...)
//}
//
//func Fatal(args ...interface{}) {
// GetLog()
// log.Fatal(args...)
//}
//
//func Panic(args ...interface{}) {
// GetLog()
// log.Panic(args...)
//}
//
//func TraceFn(fn logrus.LogFunction) {
// GetLog()
// log.TraceFn(fn)
//}
//
//func DebugFn(fn logrus.LogFunction) {
// GetLog()
// log.DebugFn(fn)
//}
//
//func InfoFn(fn logrus.LogFunction) {
// GetLog()
// log.InfoFn(fn)
//}
//
//func PrintFn(fn logrus.LogFunction) {
// GetLog()
// log.PrintFn(fn)
//}
//
//func WarnFn(fn logrus.LogFunction) {
// GetLog()
// log.WarnFn(fn)
//}
//
//func WarningFn(fn logrus.LogFunction) {
// GetLog()
// log.WarningFn(fn)
//}
//
//func ErrorFn(fn logrus.LogFunction) {
// GetLog()
// log.ErrorFn(fn)
//}
//
//func FatalFn(fn logrus.LogFunction) {
// GetLog()
// log.FatalFn(fn)
//}
//
//func PanicFn(fn logrus.LogFunction) {
// GetLog()
// log.PanicFn(fn)
//}
//
//func Logln(level logrus.Level, args ...interface{}) {
// GetLog()
// log.Logln(level, args...)
//}
//
//func Traceln(args ...interface{}) {
// GetLog()
// log.Traceln(args...)
//}
//
//func Debugln(args ...interface{}) {
// GetLog()
// log.Debugln(args...)
//}
//
//func Infoln(args ...interface{}) {
// GetLog()
// log.Infoln(args...)
//}
//
//func Println(args ...interface{}) {
// GetLog()
// log.Println(args...)
//}
//
//func Warnln(args ...interface{}) {
// GetLog()
// log.Warnln(args...)
//}
//
//func Warningln(args ...interface{}) {
// GetLog()
// log.Warningln(args...)
//}
//
//func Errorln(args ...interface{}) {
// GetLog()
// log.Errorln(args...)
//}
//
//func Fatalln(args ...interface{}) {
// GetLog()
// log.Fatalln(args...)
//}
//
//func Panicln(args ...interface{}) {
// GetLog()
// log.Panicln(args...)
//}
//
//func Exit(code int) {
// GetLog()
// log.Exit(code)
//}
//
////When file is opened with appending mode, it's safe to
////write concurrently to a file (within 4k message on Linux).
////In these cases user can choose to disable the lock.
//func SetNoLock() {
// GetLog()
// log.SetNoLock()
//}
//
////// SetLevel sets the logger level.
////func SetLevel(level logrus.Level) {
////}
//
//// GetLevel returns the logger level.
//func GetLevel() logrus.Level {
// GetLog()
// return log.GetLevel()
//}
//
//// AddHook adds a hook to the logger hooks.
//func AddHook(hook logrus.Hook) {
// GetLog()
// log.AddHook(hook)
//}
//
//// IsLevelEnabled checks if the log level of the logger is greater than the level param
//func IsLevelEnabled(level logrus.Level) bool {
// GetLog()
// return log.IsLevelEnabled(level)
//}
//
//// SetFormatter sets the logger formatter.
//func SetFormatter(formatter logrus.Formatter) {
// GetLog()
// log.SetFormatter(formatter)
//}
//
//// SetOutput sets the logger output.
//func SetOutput(output io.Writer) {
// GetLog()
// log.SetOutput(output)
//}
//
//func SetReportCaller(reportCaller bool) {
// GetLog()
// log.SetReportCaller(reportCaller)
//}
//
//// ReplaceHooks replaces the logger hooks and returns the old ones
//func ReplaceHooks(hooks logrus.LevelHooks) logrus.LevelHooks {
// GetLog()
// return ReplaceHooks(hooks)
//}
//
//// SetBufferPool sets the logger buffer pool.
//func SetBufferPool(pool logrus.BufferPool) {
// GetLog()
// log.SetBufferPool(pool)
//}

View File

@ -0,0 +1,694 @@
// модуль с вспомогательными небольшими функциями
package micro
import (
"context"
"errors"
"fmt"
"hash/fnv"
"reflect"
"runtime"
"strconv"
"strings"
"unicode"
//"log"
"os"
"path/filepath"
"time"
)
//var log = logger.GetLog()
// IsTestApp - возвращает true если это тестовая среда выполнения приложения
func IsTestApp() bool {
Otvet := true
stage, ok := os.LookupEnv("STAGE")
if ok == false {
panic(fmt.Errorf("Not found Env 'STAGE' !"))
}
switch stage {
case "local", "dev", "test", "preprod":
Otvet = true
case "prod":
Otvet = false
default:
panic(fmt.Errorf("Error, unknown stage(%v) !", stage))
}
return Otvet
}
// FileExists - возвращает true если файл существует
func FileExists(name string) (bool, error) {
_, err := os.Stat(name)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
// AddSeparator - добавляет в конец строки сеператор "/", если его там нет
func AddSeparator(dir string) string {
otvet := dir
if otvet == "" {
return SeparatorFile()
}
if otvet[len(otvet)-1:] != SeparatorFile() {
otvet = otvet + SeparatorFile()
}
return otvet
}
// SeparatorFile - возвращает символ сепаратора каталогов= / или \
func SeparatorFile() string {
return string(filepath.Separator)
}
// Sleep - приостановка работы программы на нужное число миллисекунд
func Sleep(ms int) {
duration := time.Duration(ms) * time.Millisecond
time.Sleep(duration)
}
// Pause - приостановка работы программы на нужное число миллисекунд
func Pause(ms int) {
Sleep(ms)
}
// FindDirUp - возвращает строку с именем каталога на уровень выше
func FindDirUp(dir string) string {
otvet := dir
if dir == "" {
return otvet
}
if otvet[len(otvet)-1:] == SeparatorFile() {
otvet = otvet[:len(otvet)-1]
}
pos1 := strings.LastIndex(otvet, SeparatorFile())
if pos1 > 0 {
otvet = otvet[0 : pos1+1]
}
return otvet
}
// ErrorJoin - возвращает ошибку из объединения текста двух ошибок
func ErrorJoin(err1, err2 error) error {
var err error
if err1 == nil && err2 == nil {
} else if err1 == nil {
err = err2
} else if err2 == nil {
err = err1
} else {
err = errors.New(err1.Error() + ", " + err2.Error())
}
return err
}
// SubstringLeft - возвращает левые символы строки
func SubstringLeft(str string, num int) string {
if num <= 0 {
return ``
}
if num > len(str) {
num = len(str)
}
return str[:num]
}
// SubstringRight - возвращает правые символы строки
func SubstringRight(str string, num int) string {
if num <= 0 {
return ``
}
max := len(str)
if num > max {
num = max
}
num = max - num
return str[num:]
}
// StringBetween - GetStringInBetween Returns empty string if no start string found
func StringBetween(str string, start string, end string) string {
otvet := ""
if str == "" {
return otvet
}
pos1 := strings.Index(str, start)
if pos1 == -1 {
return otvet
}
pos1 += len(start)
pos2 := strings.Index(str[pos1:], end)
if pos2 == -1 {
return otvet
}
pos2 = pos1 + pos2
otvet = str[pos1:pos2]
return otvet
}
// LastWord - возвращает последнее слово из строки
func LastWord(StringFrom string) string {
Otvet := ""
if StringFrom == "" {
return Otvet
}
r := []rune(StringFrom)
for f := len(r); f >= 0; f-- {
r1 := r[f-1]
if r1 == '_' {
} else if unicode.IsLetter(r1) == false && unicode.IsDigit(r1) == false {
break
}
Otvet = string(r1) + Otvet
}
return Otvet
}
// CurrentFilename - возвращает полное имя текущего исполняемого файла
func CurrentFilename() string {
_, filename, _, _ := runtime.Caller(0)
return filename
}
// ProgramDir - возвращает главный каталог программы, в конце "/"
func ProgramDir_Common() string {
//filename := os.Args[0]
filename, err := os.Executable()
if err != nil {
panic(err)
}
dir := filepath.Dir(filename)
sdir := strings.ToLower(dir)
substr := "/tmp/"
pos1 := strings.Index(sdir, substr)
if pos1 >= 0 {
//linux
filename = CurrentFilename()
dir = filepath.Dir(filename)
substr := SeparatorFile() + "vendor" + SeparatorFile()
pos_vendor := strings.Index(strings.ToLower(dir), substr)
if pos_vendor >= 0 {
dir = dir[0:pos_vendor]
} else if dir[len(dir)-5:] == "micro" {
dir = FindDirUp(dir)
//dir = FindDirUp(dir)
//dir = FindDirUp(dir)
}
} else {
//Windows
substr = "\\temp\\"
pos1 = strings.Index(sdir, substr)
if pos1 >= 0 {
filename = CurrentFilename()
dir = filepath.Dir(filename)
substr := SeparatorFile() + "vendor" + SeparatorFile()
pos_vendor := strings.Index(strings.ToLower(dir), substr)
if pos_vendor >= 0 {
dir = dir[0:pos_vendor]
} else if dir[len(dir)-5:] == "micro" {
dir = FindDirUp(dir)
//dir = FindDirUp(dir)
//dir = FindDirUp(dir)
}
}
}
//dir, err := os.Getwd()
//if err != nil {
// log.Fatalln(err)
// dir = ""
//}
dir = AddSeparator(dir)
return dir
}
// ProgramDir - возвращает главный каталог программы, в конце "/"
func ProgramDir() string {
Otvet := ProgramDir_Common()
return Otvet
}
// FileNameWithoutExtension - возвращает имя файла без расширения
func FileNameWithoutExtension(fileName string) string {
return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}
func BeginningOfMonth(date time.Time) time.Time {
return date.AddDate(0, 0, -date.Day()+1)
}
func EndOfMonth(date time.Time) time.Time {
Otvet := date.AddDate(0, 1, -date.Day())
return Otvet
//return date.AddDate(0, 1, -date.Day())
}
//// GetPackageName - возвращает имя пакета
//func GetPackageName(temp interface{}) string {
// strs := strings.Split((runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name()), ".")
// strs = strings.Split(strs[len(strs)-2], "/")
// return strs[len(strs)-1]
//}
// StringAfter - возвращает строку, начиная после субстроки StringAfter
func StringAfter(StringFull, StringAfter string) string {
Otvet := StringFull
pos1 := strings.Index(StringFull, StringAfter)
if pos1 == -1 {
return Otvet
}
Otvet = Otvet[pos1+len(StringAfter):]
return Otvet
}
// StringFrom - возвращает строку, начиная со субстроки StringAfter
func StringFrom(StringFull, StringAfter string) string {
Otvet := StringFull
pos1 := strings.Index(StringFull, StringAfter)
if pos1 == -1 {
return Otvet
}
Otvet = Otvet[pos1:]
return Otvet
}
func Trim(s string) string {
Otvet := ""
Otvet = strings.Trim(s, " \n\r\t")
return Otvet
}
// Max returns the largest of x or y.
func Max(x, y int) int {
if x < y {
return y
}
return x
}
// Min returns the smallest of x or y.
func Min(x, y int) int {
if x > y {
return y
}
return x
}
// Max returns the largest of x or y.
func MaxInt64(x, y int64) int64 {
if x < y {
return y
}
return x
}
// Min returns the smallest of x or y.
func MinInt64(x, y int64) int64 {
if x > y {
return y
}
return x
}
// MaxDate returns the largest of x or y.
func MaxDate(x, y time.Time) time.Time {
if x.Before(y) == true {
return y
}
return x
}
// MinDate returns the smallest of x or y.
func MinDate(x, y time.Time) time.Time {
if x.Before(y) == false {
return y
}
return x
}
// GoGo - запускает функцию в отдельном потоке
func GoGo(ctx context.Context, fn func() error) error {
var err error
chanErr := make(chan error)
go gogo_chan(fn, chanErr)
select {
case <-ctx.Done():
Text1 := "error: TimeOut"
err = errors.New(Text1)
return err
case err = <-chanErr:
//print("err: ", err)
break
}
return err
}
// gogo_chan - запускает функцию и возвращает ошибку в поток
// только совместно с GoGo()
func gogo_chan(fn func() error, chanErr chan error) {
err := fn()
chanErr <- err
}
// CheckInnKpp - проверяет правильность ИНН и КПП
func CheckInnKpp(Inn, Kpp string, is_individual bool) error {
var err error
if Inn == "" {
Text1 := "ИНН не должен быть пустой"
err = errors.New(Text1)
return err
}
if is_individual == true {
if len(Inn) != 12 {
Text1 := "Длина ИНН должна быть 12 символов"
err = errors.New(Text1)
return err
}
if len(Kpp) != 0 {
Text1 := "КПП должен быть пустой"
err = errors.New(Text1)
return err
}
} else {
if len(Inn) != 10 {
Text1 := "Длина ИНН должна быть 10 символов"
err = errors.New(Text1)
return err
}
if len(Kpp) != 9 {
Text1 := "КПП должен быть 9 символов"
err = errors.New(Text1)
return err
}
err = CheckINNControlSum(Inn)
}
return err
}
// CheckINNControlSum - проверяет правильность ИНН по контрольной сумме
func CheckINNControlSum(Inn string) error {
var err error
if len(Inn) == 10 {
err = CheckINNControlSum10(Inn)
} else if len(Inn) == 12 {
err = CheckINNControlSum12(Inn)
} else {
err = errors.New("ИНН должен быть 10 или 12 символов")
}
return err
}
// CheckINNControlSum10 - проверяет правильность 10-значного ИНН по контрольной сумме
func CheckINNControlSum10(Inn string) error {
var err error
MassKoef := [10]int{2, 4, 10, 3, 5, 9, 4, 6, 8, 0}
var sum int
var x int
for i, _ := range Inn {
s := Inn[i : i+1]
var err1 error
x, err1 = strconv.Atoi(s)
if err1 != nil {
err = errors.New("Неправильная цифра в ИНН: " + s)
return err
}
sum = sum + x*MassKoef[i]
}
ControlSum := sum % 11
ControlSum = ControlSum % 10
if ControlSum != x {
err = errors.New("Неправильная контрольная сумма ИНН")
return err
}
return err
}
// CheckINNControlSum2 - проверяет правильность 12-значного ИНН по контрольной сумме
func CheckINNControlSum12(Inn string) error {
var err error
//контрольное чилос по 11 знакам
MassKoef := [11]int{7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0}
var sum int
var x11 int
for i := 0; i < 11; i++ {
s := Inn[i : i+1]
var err1 error
x, err1 := strconv.Atoi(s)
if err1 != nil {
err = errors.New("Неправильная цифра в ИНН: " + s)
return err
}
if i == 10 {
x11 = x
}
sum = sum + x*MassKoef[i]
}
ControlSum := sum % 11
ControlSum = ControlSum % 10
if ControlSum != x11 {
err = errors.New("Неправильная контрольная сумма ИНН")
return err
}
//контрольное чилос по 12 знакам
MassKoef2 := [12]int{3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0}
var sum2 int
var x12 int
for i := 0; i < 12; i++ {
s := Inn[i : i+1]
var err1 error
x, err1 := strconv.Atoi(s)
if err1 != nil {
err = errors.New("Неправильная цифра в ИНН: " + s)
return err
}
if i == 11 {
x12 = x
}
sum2 = sum2 + x*MassKoef2[i]
}
ControlSum2 := sum2 % 11
ControlSum2 = ControlSum2 % 10
if ControlSum2 != x12 {
err = errors.New("Неправильная контрольная сумма ИНН")
return err
}
return err
}
// StringFromInt64 - возвращает строку из числа
func StringFromInt64(i int64) string {
Otvet := ""
Otvet = strconv.FormatInt(i, 10)
return Otvet
}
// StringDate - возвращает строку дата без времени
func StringDate(t time.Time) string {
Otvet := ""
Otvet = t.Format("02.01.2006")
return Otvet
}
// ProgramDir_bin - возвращает каталог "bin" или каталог программы
func ProgramDir_bin() string {
Otvet := ""
dir := ProgramDir()
FileName := dir + "bin" + SeparatorFile()
ok, _ := FileExists(FileName)
if ok == true {
return FileName
}
Otvet = dir
return Otvet
}
// SaveTempFile - записывает массив байт в файл
func SaveTempFile(bytes []byte) string {
Otvet, err := SaveTempFile_err(bytes)
if err != nil {
TextError := fmt.Sprint("SaveTempFile() error: ", err)
print(TextError)
panic(TextError)
}
return Otvet
}
// SaveTempFile_err - записывает массив байт в файл, возвращает ошибку
func SaveTempFile_err(bytes []byte) (string, error) {
Otvet := ""
// create and open a temporary file
f, err := os.CreateTemp("", "") // in Go version older than 1.17 you can use ioutil.TempFile
if err != nil {
return Otvet, err
}
// close and remove the temporary file at the end of the program
defer f.Close()
//defer os.Remove(f.Name())
// write data to the temporary file
if _, err := f.Write(bytes); err != nil {
return Otvet, err
}
Otvet = f.Name()
return Otvet, err
}
// Hash - возвращает число хэш из строки
func Hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}
// TextError - возвращает текст ошибки из error
func TextError(err error) string {
Otvet := ""
if err != nil {
Otvet = err.Error()
}
return Otvet
}
// GetType - возвращает строку тип объекта
func GetType(myvar interface{}) string {
return reflect.TypeOf(myvar).String()
}
// FindFileNameShort - возвращает имя файла(каталога) без пути
func FindFileNameShort(path string) string {
Otvet := ""
if path == "" {
return Otvet
}
Otvet = filepath.Base(path)
return Otvet
}
// CurrentDirectory - возвращает текущую директорию ОС
func CurrentDirectory() string {
Otvet, err := os.Getwd()
if err != nil {
//log.Println(err)
}
return Otvet
}
// BoolFromInt64 - возвращает true если число <>0
func BoolFromInt64(i int64) bool {
Otvet := false
if i != 0 {
Otvet = true
}
return Otvet
}
// BoolFromInt - возвращает true если число <>0
func BoolFromInt(i int) bool {
Otvet := false
if i != 0 {
Otvet = true
}
return Otvet
}
// DeleteFileSeperator - убирает в конце / или \
func DeleteFileSeperator(dir string) string {
Otvet := dir
len1 := len(Otvet)
if len1 == 0 {
return Otvet
}
LastWord := Otvet[len1-1 : len1]
if LastWord == SeparatorFile() {
Otvet = Otvet[0 : len1-1]
}
return Otvet
}

42
vendor/github.com/ManyakRus/starter/ping/ping.go generated vendored Normal file
View File

@ -0,0 +1,42 @@
package ping
import (
"github.com/ManyakRus/starter/logger"
"net"
"time"
)
// log - глобальный логгер
var log = logger.GetLog()
func Ping_err(IP, Port string) error {
var err error
var timeout time.Duration
timeout = time.Second * 3
network := IP + ":" + Port
conn, err := net.DialTimeout("tcp", network, timeout)
if err != nil {
//log.Warn("PingPort() error: ", err)
} else {
defer conn.Close()
//log.Debug("ping OK: ", network)
}
return err
}
func Ping(IP, Port string) {
var err error
network := IP + ":" + Port
err = Ping_err(IP, Port)
if err != nil {
log.Panic("Ping() error: ", err)
} else {
log.Debug("Ping() OK: ", network)
}
}

View File

@ -0,0 +1,349 @@
// модуль для работы с базой данных
package postgres_gorm
import (
"context"
"errors"
"github.com/ManyakRus/starter/logger"
"github.com/ManyakRus/starter/ping"
"time"
//"github.com/jackc/pgconn"
"os"
"sync"
//"time"
//"github.com/jmoiron/sqlx"
//_ "github.com/lib/pq"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/micro"
"github.com/ManyakRus/starter/stopapp"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
// Conn - соединение к базе данных
var Conn *gorm.DB
// log - глобальный логгер
var log = logger.GetLog()
// mutexReconnect - защита от многопоточности Reconnect()
var mutexReconnect = &sync.Mutex{}
// Settings хранит все нужные переменные окружения
var Settings SettingsINI
// NeedReconnect - флаг необходимости переподключения
var NeedReconnect bool
// SettingsINI - структура для хранения всех нужных переменных окружения
type SettingsINI struct {
DB_HOST string
DB_PORT string
DB_NAME string
DB_SCHEMA string
DB_USER string
DB_PASSWORD string
}
// Connect_err - подключается к базе данных
func Connect() {
if Settings.DB_HOST == "" {
FillSettings()
}
ping.Ping(Settings.DB_HOST, Settings.DB_PORT)
err := Connect_err()
if err != nil {
log.Panicln("POSTGRES gorm Connect() to database host: ", Settings.DB_HOST, ", Error: ", err)
} else {
log.Info("POSTGRES gorm Connected. host: ", Settings.DB_HOST, ", base name: ", Settings.DB_NAME, ", schema: ", Settings.DB_SCHEMA)
}
}
// Connect_err - подключается к базе данных
func Connect_err() error {
var err error
if Settings.DB_HOST == "" {
FillSettings()
}
//ctxMain := context.Background()
//ctxMain := contextmain.GetContext()
//ctx, cancel := context.WithTimeout(ctxMain, 5*time.Second)
//defer cancel()
// get the database connection URL.
dsn := GetDSN()
//
conf := &gorm.Config{}
conn := postgres.Open(dsn)
Conn, err = gorm.Open(conn, conf)
Conn.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: Settings.DB_SCHEMA + "."}
Conn.Config.Logger = gormlogger.Default.LogMode(gormlogger.Warn)
if err == nil {
DB, err := Conn.DB()
if err != nil {
log.Error("Conn.DB() error: ", err)
return err
}
err = DB.Ping()
}
return err
}
// IsClosed проверка что база данных закрыта
func IsClosed() bool {
var otvet bool
if Conn == nil {
return true
}
DB, err := Conn.DB()
if err != nil {
log.Error("Conn.DB() error: ", err)
return true
}
err = DB.Ping()
if err != nil {
log.Error("DB.Ping() error: ", err)
return true
}
return otvet
}
// Reconnect повторное подключение к базе данных, если оно отключено
// или полная остановка программы
func Reconnect(err error) {
mutexReconnect.Lock()
defer mutexReconnect.Unlock()
if err == nil {
return
}
if errors.Is(err, context.Canceled) {
return
}
if Conn == nil {
log.Warn("Reconnect()")
err := Connect_err()
if err != nil {
log.Error("error: ", err)
}
return
}
if IsClosed() {
micro.Pause(1000)
log.Warn("Reconnect()")
err := Connect_err()
if err != nil {
log.Error("error: ", err)
}
return
}
sError := err.Error()
if sError == "Conn closed" {
micro.Pause(1000)
log.Warn("Reconnect()")
err := Connect_err()
if err != nil {
log.Error("error: ", err)
}
return
}
//PgError, ok := err.(*pgconn.PgError)
//if ok {
// if PgError.Code == "P0001" { // Class P0 — PL/pgSQL Error, RaiseException
// return //нужен
// }
//}
//остановим программу т.к. она не должна работать при неработающеё БД
log.Error("STOP app. Error: ", err)
stopapp.StopApp()
}
// CloseConnection - закрытие соединения с базой данных
func CloseConnection() {
if Conn == nil {
return
}
err := CloseConnection_err()
if err != nil {
log.Error("Postgres gorm CloseConnection() error: ", err)
} else {
log.Info("Postgres gorm connection closed")
}
return
}
// CloseConnection - закрытие соединения с базой данных
func CloseConnection_err() error {
if Conn == nil {
return nil
}
DB, err := Conn.DB()
if err != nil {
log.Error("Conn.DB() error: ", err)
return err
}
err = DB.Close()
if err != nil {
log.Error("DB.Close() error: ", err)
}
Conn = nil
return err
}
// WaitStop - ожидает отмену глобального контекста
func WaitStop() {
select {
case <-contextmain.GetContext().Done():
log.Warn("Context app is canceled.")
}
//
stopapp.WaitTotalMessagesSendingNow("Postgres gorm")
//
CloseConnection()
stopapp.GetWaitGroup_Main().Done()
}
// StartDB - делает соединение с БД, отключение и др.
func StartDB() {
Connect()
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
stopapp.GetWaitGroup_Main().Add(1)
go ping_go()
}
// FillSettings загружает переменные окружения в структуру из файла или из переменных окружения
func FillSettings() {
Settings = SettingsINI{}
// заполним из переменных оуружения
Settings.DB_HOST = os.Getenv("DB_HOST")
Settings.DB_PORT = os.Getenv("DB_PORT")
Settings.DB_NAME = os.Getenv("DB_NAME")
Settings.DB_SCHEMA = os.Getenv("DB_SCHEME")
Settings.DB_USER = os.Getenv("DB_USER")
Settings.DB_PASSWORD = os.Getenv("DB_PASSWORD")
//// заполним из переменных оуружения как у Нечаева
//if Settings.DB_HOST == "" {
// Settings.DB_HOST = os.Getenv("STORE_HOST")
// Settings.DB_PORT = os.Getenv("STORE_PORT")
// Settings.DB_NAME = os.Getenv("STORE_NAME")
// Settings.DB_SCHEMA = os.Getenv("STORE_SCHEME")
// Settings.DB_USER = os.Getenv("STORE_LOGIN")
// Settings.DB_PASSWORD = os.Getenv("STORE_PASSWORD")
//}
if Settings.DB_HOST == "" {
log.Panicln("Need fill DB_HOST ! in os.ENV ")
}
if Settings.DB_PORT == "" {
log.Panicln("Need fill DB_PORT ! in os.ENV ")
}
if Settings.DB_NAME == "" {
log.Panicln("Need fill DB_NAME ! in os.ENV ")
}
if Settings.DB_SCHEMA == "" {
log.Panicln("Need fill DB_SCHEMA ! in os.ENV ")
}
if Settings.DB_USER == "" {
log.Panicln("Need fill DB_USER ! in os.ENV ")
}
if Settings.DB_PASSWORD == "" {
log.Panicln("Need fill DB_PASSWORD ! in os.ENV ")
}
//
}
// GetDSN - возвращает строку соединения к базе данных
func GetDSN() string {
dsn := "host=" + Settings.DB_HOST + " "
dsn += "user=" + Settings.DB_USER + " "
dsn += "password=" + Settings.DB_PASSWORD + " "
dsn += "dbname=" + Settings.DB_NAME + " "
dsn += "port=" + Settings.DB_PORT + " sslmode=disable TimeZone=UTC"
return dsn
}
// GetConnection - возвращает соединение к нужной базе данных
func GetConnection() *gorm.DB {
if Conn == nil {
Connect()
}
return Conn
}
// ping_go - делает пинг каждые 60 секунд, и реконнект
func ping_go() {
ticker := time.NewTicker(60 * time.Second)
addr := Settings.DB_HOST + ":" + Settings.DB_PORT
//бесконечный цикл
loop:
for {
select {
case <-contextmain.GetContext().Done():
log.Warn("Context app is canceled. postgres_gorm.ping")
break loop
case <-ticker.C:
err := ping.Ping_err(Settings.DB_HOST, Settings.DB_PORT)
//log.Debug("ticker, ping err: ", err) //удалить
if err != nil {
NeedReconnect = true
log.Warn("postgres_gorm Ping(", addr, ") error: ", err)
} else if NeedReconnect == true {
log.Warn("postgres_gorm Ping(", addr, ") OK. Start Reconnect()")
NeedReconnect = false
Connect()
}
}
}
stopapp.GetWaitGroup_Main().Done()
}

127
vendor/github.com/ManyakRus/starter/stopapp/stopapp.go generated vendored Normal file
View File

@ -0,0 +1,127 @@
// модуль для корректной остановки работы приложения
package stopapp
import (
"github.com/ManyakRus/starter/logger"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
//"github.com/sirupsen/logrus"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/micro"
// "gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/micro"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/db"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/grpcserver"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/logger"
//"gitlab.aescorp.ru/dsp_dev/notifier/notifier_adp_eml/internal/v0/app/micro"
)
// log - глобальный логгер
var log = logger.GetLog()
// SignalInterrupt - канал для ожидания сигнала остановки приложения
var SignalInterrupt chan os.Signal
// wgMain - группа ожидания завершения всех частей программы
var wgMain *sync.WaitGroup
// lockWGMain - гарантирует получение WGMain с учётом многопоточности
var lockWGMain = &sync.Mutex{}
// onceWGMain - гарантирует создание WGMain один раз
var onceWGMain sync.Once
// TotalMessagesSendingNow - количество сообщений отправляющихся прям сейчас
var TotalMessagesSendingNow int32
// SecondsWaitTotalMessagesSendingNow - количество секунд ожидания для отправки последнего сообщения
const SecondsWaitTotalMessagesSendingNow = 10
// SetWaitGroup_Main - присваивает внешний WaitGroup
func SetWaitGroup_Main(wg *sync.WaitGroup) {
wgMain = wg
}
// GetWaitGroup_Main - возвращает группу ожидания завершения всех частей программы
func GetWaitGroup_Main() *sync.WaitGroup {
lockWGMain.Lock()
defer lockWGMain.Unlock()
//
//if wgMain == nil {
// wgMain = &sync.WaitGroup{}
//}
if wgMain == nil {
//onceWGMain.Do(func() {
wgMain = &sync.WaitGroup{}
//})
}
return wgMain
}
// StartWaitStop - запускает ожидание сигнала завершения приложения
func StartWaitStop() {
SignalInterrupt = make(chan os.Signal, 1)
fnWait := func() {
signal.Notify(SignalInterrupt, os.Interrupt, syscall.SIGTERM)
}
go fnWait()
GetWaitGroup_Main().Add(1)
go WaitStop()
}
// StopApp - отмена глобального контекста для остановки работы приложения
func StopApp() {
if contextmain.CancelContext != nil {
contextmain.CancelContext()
} else {
//os.Exit(0)
log.Warn("Context = nil")
}
}
// StopApp - отмена глобального контекста для остановки работы приложения
func StopAppAndWait() {
if contextmain.CancelContext != nil {
contextmain.CancelContext()
} else {
os.Exit(0)
}
GetWaitGroup_Main().Wait()
}
// WaitStop - ожидает отмену глобального контекста или сигнала завершения приложения
func WaitStop() {
select {
case <-SignalInterrupt:
log.Warn("Interrupt clean shutdown.")
contextmain.CancelContext()
case <-contextmain.GetContext().Done():
log.Warn("Context app is canceled.")
}
GetWaitGroup_Main().Done()
}
// ожидает чтоб прям щас ничего не отправлялось
func WaitTotalMessagesSendingNow(filename string) {
for f := 0; f < SecondsWaitTotalMessagesSendingNow; f++ {
TotalMessages := atomic.LoadInt32(&TotalMessagesSendingNow)
if TotalMessages == 0 {
break
}
log.Warn("TotalMessagesSendingNow =", TotalMessages, " !=0 sleep(1000), filename: ", filename)
micro.Sleep(1000)
}
}

12
vendor/github.com/beevik/etree/CONTRIBUTORS generated vendored Normal file
View File

@ -0,0 +1,12 @@
Brett Vickers (beevik)
Felix Geisendörfer (felixge)
Kamil Kisiel (kisielk)
Graham King (grahamking)
Matt Smith (ma314smith)
Michal Jemala (michaljemala)
Nicolas Piganeau (npiganeau)
Chris Brown (ccbrown)
Earncef Sequeira (earncef)
Gabriel de Labachelerie (wuzuf)
Martin Dosch (mdosch)
Hugo Wetterberg (hugowetterberg)

24
vendor/github.com/beevik/etree/LICENSE generated vendored Normal file
View File

@ -0,0 +1,24 @@
Copyright 2015-2023 Brett Vickers. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

204
vendor/github.com/beevik/etree/README.md generated vendored Normal file
View File

@ -0,0 +1,204 @@
[![GoDoc](https://godoc.org/github.com/beevik/etree?status.svg)](https://godoc.org/github.com/beevik/etree)
etree
=====
The etree package is a lightweight, pure go package that expresses XML in
the form of an element tree. Its design was inspired by the Python
[ElementTree](http://docs.python.org/2/library/xml.etree.elementtree.html)
module.
Some of the package's capabilities and features:
* Represents XML documents as trees of elements for easy traversal.
* Imports, serializes, modifies or creates XML documents from scratch.
* Writes and reads XML to/from files, byte slices, strings and io interfaces.
* Performs simple or complex searches with lightweight XPath-like query APIs.
* Auto-indents XML using spaces or tabs for better readability.
* Implemented in pure go; depends only on standard go libraries.
* Built on top of the go [encoding/xml](http://golang.org/pkg/encoding/xml)
package.
### Creating an XML document
The following example creates an XML document from scratch using the etree
package and outputs its indented contents to stdout.
```go
doc := etree.NewDocument()
doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
doc.CreateProcInst("xml-stylesheet", `type="text/xsl" href="style.xsl"`)
people := doc.CreateElement("People")
people.CreateComment("These are all known people")
jon := people.CreateElement("Person")
jon.CreateAttr("name", "Jon")
sally := people.CreateElement("Person")
sally.CreateAttr("name", "Sally")
doc.Indent(2)
doc.WriteTo(os.Stdout)
```
Output:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<People>
<!--These are all known people-->
<Person name="Jon"/>
<Person name="Sally"/>
</People>
```
### Reading an XML file
Suppose you have a file on disk called `bookstore.xml` containing the
following data:
```xml
<bookstore xmlns:p="urn:schemas-books-com:prices">
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<p:price>30.00</p:price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<p:price>29.99</p:price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<p:price>49.99</p:price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<p:price>39.95</p:price>
</book>
</bookstore>
```
This code reads the file's contents into an etree document.
```go
doc := etree.NewDocument()
if err := doc.ReadFromFile("bookstore.xml"); err != nil {
panic(err)
}
```
You can also read XML from a string, a byte slice, or an `io.Reader`.
### Processing elements and attributes
This example illustrates several ways to access elements and attributes using
etree selection queries.
```go
root := doc.SelectElement("bookstore")
fmt.Println("ROOT element:", root.Tag)
for _, book := range root.SelectElements("book") {
fmt.Println("CHILD element:", book.Tag)
if title := book.SelectElement("title"); title != nil {
lang := title.SelectAttrValue("lang", "unknown")
fmt.Printf(" TITLE: %s (%s)\n", title.Text(), lang)
}
for _, attr := range book.Attr {
fmt.Printf(" ATTR: %s=%s\n", attr.Key, attr.Value)
}
}
```
Output:
```
ROOT element: bookstore
CHILD element: book
TITLE: Everyday Italian (en)
ATTR: category=COOKING
CHILD element: book
TITLE: Harry Potter (en)
ATTR: category=CHILDREN
CHILD element: book
TITLE: XQuery Kick Start (en)
ATTR: category=WEB
CHILD element: book
TITLE: Learning XML (en)
ATTR: category=WEB
```
### Path queries
This example uses etree's path functions to select all book titles that fall
into the category of 'WEB'. The double-slash prefix in the path causes the
search for book elements to occur recursively; book elements may appear at any
level of the XML hierarchy.
```go
for _, t := range doc.FindElements("//book[@category='WEB']/title") {
fmt.Println("Title:", t.Text())
}
```
Output:
```
Title: XQuery Kick Start
Title: Learning XML
```
This example finds the first book element under the root bookstore element and
outputs the tag and text of each of its child elements.
```go
for _, e := range doc.FindElements("./bookstore/book[1]/*") {
fmt.Printf("%s: %s\n", e.Tag, e.Text())
}
```
Output:
```
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
price: 30.00
```
This example finds all books with a price of 49.99 and outputs their titles.
```go
path := etree.MustCompilePath("./bookstore/book[p:price='49.99']/title")
for _, e := range doc.FindElementsPath(path) {
fmt.Println(e.Text())
}
```
Output:
```
XQuery Kick Start
```
Note that this example uses the FindElementsPath function, which takes as an
argument a pre-compiled path object. Use precompiled paths when you plan to
search with the same path more than once.
### Other features
These are just a few examples of the things the etree package can do. See the
[documentation](http://godoc.org/github.com/beevik/etree) for a complete
description of its capabilities.
### Contributing
This project accepts contributions. Just fork the repo and submit a pull
request!

153
vendor/github.com/beevik/etree/RELEASE_NOTES.md generated vendored Normal file
View File

@ -0,0 +1,153 @@
Release v1.2.0
==============
**New Features**
* Add the ability to write XML fragments using Token WriteTo functions.
* Add the ability to re-indent an XML element as though it were the root of
the document.
* Add a ReadSettings option to preserve CDATA blocks when reading and XML
document.
Release v1.1.4
==============
**New Features**
* Add the ability to preserve whitespace in leaf elements during indent.
* Add the ability to suppress a document-trailing newline during indent.
* Add choice of XML attribute quoting style (single-quote or double-quote).
**Removed Features**
* Removed the CDATA preservation change introduced in v1.1.3. It was
implemented in a way that broke the ability to process XML documents
encoded using non-UTF8 character sets.
Release v1.1.3
==============
* XML reads now preserve CDATA sections instead of converting them to
standard character data.
Release v1.1.2
==============
* Fixed a path parsing bug.
* The `Element.Text` function now handles comments embedded between
character data spans.
Release v1.1.1
==============
* Updated go version in `go.mod` to 1.20
Release v1.1.0
==============
**New Features**
* New attribute helpers.
* Added the `Element.SortAttrs` method, which lexicographically sorts an
element's attributes by key.
* New `ReadSettings` properties.
* Added `Entity` for the support of custom entity maps.
* New `WriteSettings` properties.
* Added `UseCRLF` to allow the output of CR-LF newlines instead of the
default LF newlines. This is useful on Windows systems.
* Additional support for text and CDATA sections.
* The `Element.Text` method now returns the concatenation of all consecutive
character data tokens immediately following an element's opening tag.
* Added `Element.SetCData` to replace the character data immediately
following an element's opening tag with a CDATA section.
* Added `Element.CreateCData` to create and add a CDATA section child
`CharData` token to an element.
* Added `Element.CreateText` to create and add a child text `CharData` token
to an element.
* Added `NewCData` to create a parentless CDATA section `CharData` token.
* Added `NewText` to create a parentless text `CharData`
token.
* Added `CharData.IsCData` to detect if the token contains a CDATA section.
* Added `CharData.IsWhitespace` to detect if the token contains whitespace
inserted by one of the document Indent functions.
* Modified `Element.SetText` so that it replaces a run of consecutive
character data tokens following the element's opening tag (instead of just
the first one).
* New "tail text" support.
* Added the `Element.Tail` method, which returns the text immediately
following an element's closing tag.
* Added the `Element.SetTail` method, which modifies the text immediately
following an element's closing tag.
* New element child insertion and removal methods.
* Added the `Element.InsertChildAt` method, which inserts a new child token
before the specified child token index.
* Added the `Element.RemoveChildAt` method, which removes the child token at
the specified child token index.
* New element and attribute queries.
* Added the `Element.Index` method, which returns the element's index within
its parent element's child token list.
* Added the `Element.NamespaceURI` method to return the namespace URI
associated with an element.
* Added the `Attr.NamespaceURI` method to return the namespace URI
associated with an element.
* Added the `Attr.Element` method to return the element that an attribute
belongs to.
* New Path filter functions.
* Added `[local-name()='val']` to keep elements whose unprefixed tag matches
the desired value.
* Added `[name()='val']` to keep elements whose full tag matches the desired
value.
* Added `[namespace-prefix()='val']` to keep elements whose namespace prefix
matches the desired value.
* Added `[namespace-uri()='val']` to keep elements whose namespace URI
matches the desired value.
**Bug Fixes**
* A default XML `CharSetReader` is now used to prevent failed parsing of XML
documents using certain encodings.
([Issue](https://github.com/beevik/etree/issues/53)).
* All characters are now properly escaped according to XML parsing rules.
([Issue](https://github.com/beevik/etree/issues/55)).
* The `Document.Indent` and `Document.IndentTabs` functions no longer insert
empty string `CharData` tokens.
**Deprecated**
* `Element`
* The `InsertChild` method is deprecated. Use `InsertChildAt` instead.
* The `CreateCharData` method is deprecated. Use `CreateText` instead.
* `CharData`
* The `NewCharData` method is deprecated. Use `NewText` instead.
Release v1.0.1
==============
**Changes**
* Added support for absolute etree Path queries. An absolute path begins with
`/` or `//` and begins its search from the element's document root.
* Added [`GetPath`](https://godoc.org/github.com/beevik/etree#Element.GetPath)
and [`GetRelativePath`](https://godoc.org/github.com/beevik/etree#Element.GetRelativePath)
functions to the [`Element`](https://godoc.org/github.com/beevik/etree#Element)
type.
**Breaking changes**
* A path starting with `//` is now interpreted as an absolute path.
Previously, it was interpreted as a relative path starting from the element
whose
[`FindElement`](https://godoc.org/github.com/beevik/etree#Element.FindElement)
method was called. To remain compatible with this release, all paths
prefixed with `//` should be prefixed with `.//` when called from any
element other than the document's root.
* [**edit 2/1/2019**]: Minor releases should not contain breaking changes.
Even though this breaking change was very minor, it was a mistake to include
it in this minor release. In the future, all breaking changes will be
limited to major releases (e.g., version 2.0.0).
Release v1.0.0
==============
Initial release.

1666
vendor/github.com/beevik/etree/etree.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

394
vendor/github.com/beevik/etree/helpers.go generated vendored Normal file
View File

@ -0,0 +1,394 @@
// Copyright 2015-2019 Brett Vickers.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package etree
import (
"io"
"strings"
"unicode/utf8"
)
// A simple stack
type stack struct {
data []interface{}
}
func (s *stack) empty() bool {
return len(s.data) == 0
}
func (s *stack) push(value interface{}) {
s.data = append(s.data, value)
}
func (s *stack) pop() interface{} {
value := s.data[len(s.data)-1]
s.data[len(s.data)-1] = nil
s.data = s.data[:len(s.data)-1]
return value
}
func (s *stack) peek() interface{} {
return s.data[len(s.data)-1]
}
// A fifo is a simple first-in-first-out queue.
type fifo struct {
data []interface{}
head, tail int
}
func (f *fifo) add(value interface{}) {
if f.len()+1 >= len(f.data) {
f.grow()
}
f.data[f.tail] = value
if f.tail++; f.tail == len(f.data) {
f.tail = 0
}
}
func (f *fifo) remove() interface{} {
value := f.data[f.head]
f.data[f.head] = nil
if f.head++; f.head == len(f.data) {
f.head = 0
}
return value
}
func (f *fifo) len() int {
if f.tail >= f.head {
return f.tail - f.head
}
return len(f.data) - f.head + f.tail
}
func (f *fifo) grow() {
c := len(f.data) * 2
if c == 0 {
c = 4
}
buf, count := make([]interface{}, c), f.len()
if f.tail >= f.head {
copy(buf[0:count], f.data[f.head:f.tail])
} else {
hindex := len(f.data) - f.head
copy(buf[0:hindex], f.data[f.head:])
copy(buf[hindex:count], f.data[:f.tail])
}
f.data, f.head, f.tail = buf, 0, count
}
// xmlReader provides the interface by which an XML byte stream is
// processed and decoded.
type xmlReader interface {
Bytes() int64
Read(p []byte) (n int, err error)
}
// xmlSimpleReader implements a proxy reader that counts the number of
// bytes read from its encapsulated reader.
type xmlSimpleReader struct {
r io.Reader
bytes int64
}
func newXmlSimpleReader(r io.Reader) xmlReader {
return &xmlSimpleReader{r, 0}
}
func (xr *xmlSimpleReader) Bytes() int64 {
return xr.bytes
}
func (xr *xmlSimpleReader) Read(p []byte) (n int, err error) {
n, err = xr.r.Read(p)
xr.bytes += int64(n)
return n, err
}
// xmlPeekReader implements a proxy reader that counts the number of
// bytes read from its encapsulated reader. It also allows the caller to
// "peek" at the previous portions of the buffer after they have been
// parsed.
type xmlPeekReader struct {
r io.Reader
bytes int64 // total bytes read by the Read function
buf []byte // internal read buffer
bufSize int // total bytes used in the read buffer
bufOffset int64 // total bytes read when buf was last filled
window []byte // current read buffer window
peekBuf []byte // buffer used to store data to be peeked at later
peekOffset int64 // total read offset of the start of the peek buffer
}
func newXmlPeekReader(r io.Reader) *xmlPeekReader {
buf := make([]byte, 4096)
return &xmlPeekReader{
r: r,
bytes: 0,
buf: buf,
bufSize: 0,
bufOffset: 0,
window: buf[0:0],
peekBuf: make([]byte, 0),
peekOffset: -1,
}
}
func (xr *xmlPeekReader) Bytes() int64 {
return xr.bytes
}
func (xr *xmlPeekReader) Read(p []byte) (n int, err error) {
if len(xr.window) == 0 {
err = xr.fill()
if err != nil {
return 0, err
}
if len(xr.window) == 0 {
return 0, nil
}
}
if len(xr.window) < len(p) {
n = len(xr.window)
} else {
n = len(p)
}
copy(p, xr.window)
xr.window = xr.window[n:]
xr.bytes += int64(n)
return n, err
}
func (xr *xmlPeekReader) PeekPrepare(offset int64, maxLen int) {
if maxLen > cap(xr.peekBuf) {
xr.peekBuf = make([]byte, 0, maxLen)
}
xr.peekBuf = xr.peekBuf[0:0]
xr.peekOffset = offset
xr.updatePeekBuf()
}
func (xr *xmlPeekReader) PeekFinalize() []byte {
xr.updatePeekBuf()
return xr.peekBuf
}
func (xr *xmlPeekReader) fill() error {
xr.bufOffset = xr.bytes
xr.bufSize = 0
n, err := xr.r.Read(xr.buf)
if err != nil {
xr.window, xr.bufSize = xr.buf[0:0], 0
return err
}
xr.window, xr.bufSize = xr.buf[:n], n
xr.updatePeekBuf()
return nil
}
func (xr *xmlPeekReader) updatePeekBuf() {
peekRemain := cap(xr.peekBuf) - len(xr.peekBuf)
if xr.peekOffset >= 0 && peekRemain > 0 {
rangeMin := xr.peekOffset
rangeMax := xr.peekOffset + int64(cap(xr.peekBuf))
bufMin := xr.bufOffset
bufMax := xr.bufOffset + int64(xr.bufSize)
if rangeMin < bufMin {
rangeMin = bufMin
}
if rangeMax > bufMax {
rangeMax = bufMax
}
if rangeMax > rangeMin {
rangeMin -= xr.bufOffset
rangeMax -= xr.bufOffset
if int(rangeMax-rangeMin) > peekRemain {
rangeMax = rangeMin + int64(peekRemain)
}
xr.peekBuf = append(xr.peekBuf, xr.buf[rangeMin:rangeMax]...)
}
}
}
// xmlWriter implements a proxy writer that counts the number of
// bytes written by its encapsulated writer.
type xmlWriter struct {
w io.Writer
bytes int64
}
func newXmlWriter(w io.Writer) *xmlWriter {
return &xmlWriter{w: w}
}
func (xw *xmlWriter) Write(p []byte) (n int, err error) {
n, err = xw.w.Write(p)
xw.bytes += int64(n)
return n, err
}
// isWhitespace returns true if the byte slice contains only
// whitespace characters.
func isWhitespace(s string) bool {
for i := 0; i < len(s); i++ {
if c := s[i]; c != ' ' && c != '\t' && c != '\n' && c != '\r' {
return false
}
}
return true
}
// spaceMatch returns true if namespace a is the empty string
// or if namespace a equals namespace b.
func spaceMatch(a, b string) bool {
switch {
case a == "":
return true
default:
return a == b
}
}
// spaceDecompose breaks a namespace:tag identifier at the ':'
// and returns the two parts.
func spaceDecompose(str string) (space, key string) {
colon := strings.IndexByte(str, ':')
if colon == -1 {
return "", str
}
return str[:colon], str[colon+1:]
}
// Strings used by indentCRLF and indentLF
const (
indentSpaces = "\r\n "
indentTabs = "\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
)
// indentCRLF returns a CRLF newline followed by n copies of the first
// non-CRLF character in the source string.
func indentCRLF(n int, source string) string {
switch {
case n < 0:
return source[:2]
case n < len(source)-1:
return source[:n+2]
default:
return source + strings.Repeat(source[2:3], n-len(source)+2)
}
}
// indentLF returns a LF newline followed by n copies of the first non-LF
// character in the source string.
func indentLF(n int, source string) string {
switch {
case n < 0:
return source[1:2]
case n < len(source)-1:
return source[1 : n+2]
default:
return source[1:] + strings.Repeat(source[2:3], n-len(source)+2)
}
}
// nextIndex returns the index of the next occurrence of sep in s,
// starting from offset. It returns -1 if the sep string is not found.
func nextIndex(s, sep string, offset int) int {
switch i := strings.Index(s[offset:], sep); i {
case -1:
return -1
default:
return offset + i
}
}
// isInteger returns true if the string s contains an integer.
func isInteger(s string) bool {
for i := 0; i < len(s); i++ {
if (s[i] < '0' || s[i] > '9') && !(i == 0 && s[i] == '-') {
return false
}
}
return true
}
type escapeMode byte
const (
escapeNormal escapeMode = iota
escapeCanonicalText
escapeCanonicalAttr
)
// escapeString writes an escaped version of a string to the writer.
func escapeString(w Writer, s string, m escapeMode) {
var esc []byte
last := 0
for i := 0; i < len(s); {
r, width := utf8.DecodeRuneInString(s[i:])
i += width
switch r {
case '&':
esc = []byte("&amp;")
case '<':
esc = []byte("&lt;")
case '>':
if m == escapeCanonicalAttr {
continue
}
esc = []byte("&gt;")
case '\'':
if m != escapeNormal {
continue
}
esc = []byte("&apos;")
case '"':
if m == escapeCanonicalText {
continue
}
esc = []byte("&quot;")
case '\t':
if m != escapeCanonicalAttr {
continue
}
esc = []byte("&#x9;")
case '\n':
if m != escapeCanonicalAttr {
continue
}
esc = []byte("&#xA;")
case '\r':
if m == escapeNormal {
continue
}
esc = []byte("&#xD;")
default:
if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
esc = []byte("\uFFFD")
break
}
continue
}
w.WriteString(s[last : i-width])
w.Write(esc)
last = i
}
w.WriteString(s[last:])
}
func isInCharacterRange(r rune) bool {
return r == 0x09 ||
r == 0x0A ||
r == 0x0D ||
r >= 0x20 && r <= 0xD7FF ||
r >= 0xE000 && r <= 0xFFFD ||
r >= 0x10000 && r <= 0x10FFFF
}

586
vendor/github.com/beevik/etree/path.go generated vendored Normal file
View File

@ -0,0 +1,586 @@
// Copyright 2015-2019 Brett Vickers.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package etree
import (
"strconv"
"strings"
)
/*
A Path is a string that represents a search path through an etree starting
from the document root or an arbitrary element. Paths are used with the
Element object's Find* methods to locate and return desired elements.
A Path consists of a series of slash-separated "selectors", each of which may
be modified by one or more bracket-enclosed "filters". Selectors are used to
traverse the etree from element to element, while filters are used to narrow
the list of candidate elements at each node.
Although etree Path strings are structurally and behaviorally similar to XPath
strings (https://www.w3.org/TR/1999/REC-xpath-19991116/), they have a more
limited set of selectors and filtering options.
The following selectors are supported by etree paths:
. Select the current element.
.. Select the parent of the current element.
* Select all child elements of the current element.
/ Select the root element when used at the start of a path.
// Select all descendants of the current element.
tag Select all child elements with a name matching the tag.
The following basic filters are supported:
[@attrib] Keep elements with an attribute named attrib.
[@attrib='val'] Keep elements with an attribute named attrib and value matching val.
[tag] Keep elements with a child element named tag.
[tag='val'] Keep elements with a child element named tag and text matching val.
[n] Keep the n-th element, where n is a numeric index starting from 1.
The following function-based filters are supported:
[text()] Keep elements with non-empty text.
[text()='val'] Keep elements whose text matches val.
[local-name()='val'] Keep elements whose un-prefixed tag matches val.
[name()='val'] Keep elements whose full tag exactly matches val.
[namespace-prefix()] Keep elements with non-empty namespace prefixes.
[namespace-prefix()='val'] Keep elements whose namespace prefix matches val.
[namespace-uri()] Keep elements with non-empty namespace URIs.
[namespace-uri()='val'] Keep elements whose namespace URI matches val.
Below are some examples of etree path strings.
Select the bookstore child element of the root element:
/bookstore
Beginning from the root element, select the title elements of all descendant
book elements having a 'category' attribute of 'WEB':
//book[@category='WEB']/title
Beginning from the current element, select the first descendant book element
with a title child element containing the text 'Great Expectations':
.//book[title='Great Expectations'][1]
Beginning from the current element, select all child elements of book elements
with an attribute 'language' set to 'english':
./book/*[@language='english']
Beginning from the current element, select all child elements of book elements
containing the text 'special':
./book/*[text()='special']
Beginning from the current element, select all descendant book elements whose
title child element has a 'language' attribute of 'french':
.//book/title[@language='french']/..
Beginning from the current element, select all descendant book elements
belonging to the http://www.w3.org/TR/html4/ namespace:
.//book[namespace-uri()='http://www.w3.org/TR/html4/']
*/
type Path struct {
segments []segment
}
// ErrPath is returned by path functions when an invalid etree path is provided.
type ErrPath string
// Error returns the string describing a path error.
func (err ErrPath) Error() string {
return "etree: " + string(err)
}
// CompilePath creates an optimized version of an XPath-like string that
// can be used to query elements in an element tree.
func CompilePath(path string) (Path, error) {
var comp compiler
segments := comp.parsePath(path)
if comp.err != ErrPath("") {
return Path{nil}, comp.err
}
return Path{segments}, nil
}
// MustCompilePath creates an optimized version of an XPath-like string that
// can be used to query elements in an element tree. Panics if an error
// occurs. Use this function to create Paths when you know the path is
// valid (i.e., if it's hard-coded).
func MustCompilePath(path string) Path {
p, err := CompilePath(path)
if err != nil {
panic(err)
}
return p
}
// A segment is a portion of a path between "/" characters.
// It contains one selector and zero or more [filters].
type segment struct {
sel selector
filters []filter
}
func (seg *segment) apply(e *Element, p *pather) {
seg.sel.apply(e, p)
for _, f := range seg.filters {
f.apply(p)
}
}
// A selector selects XML elements for consideration by the
// path traversal.
type selector interface {
apply(e *Element, p *pather)
}
// A filter pares down a list of candidate XML elements based
// on a path filter in [brackets].
type filter interface {
apply(p *pather)
}
// A pather is helper object that traverses an element tree using
// a Path object. It collects and deduplicates all elements matching
// the path query.
type pather struct {
queue fifo
results []*Element
inResults map[*Element]bool
candidates []*Element
scratch []*Element // used by filters
}
// A node represents an element and the remaining path segments that
// should be applied against it by the pather.
type node struct {
e *Element
segments []segment
}
func newPather() *pather {
return &pather{
results: make([]*Element, 0),
inResults: make(map[*Element]bool),
candidates: make([]*Element, 0),
scratch: make([]*Element, 0),
}
}
// traverse follows the path from the element e, collecting
// and then returning all elements that match the path's selectors
// and filters.
func (p *pather) traverse(e *Element, path Path) []*Element {
for p.queue.add(node{e, path.segments}); p.queue.len() > 0; {
p.eval(p.queue.remove().(node))
}
return p.results
}
// eval evaluates the current path node by applying the remaining
// path's selector rules against the node's element.
func (p *pather) eval(n node) {
p.candidates = p.candidates[0:0]
seg, remain := n.segments[0], n.segments[1:]
seg.apply(n.e, p)
if len(remain) == 0 {
for _, c := range p.candidates {
if in := p.inResults[c]; !in {
p.inResults[c] = true
p.results = append(p.results, c)
}
}
} else {
for _, c := range p.candidates {
p.queue.add(node{c, remain})
}
}
}
// A compiler generates a compiled path from a path string.
type compiler struct {
err ErrPath
}
// parsePath parses an XPath-like string describing a path
// through an element tree and returns a slice of segment
// descriptors.
func (c *compiler) parsePath(path string) []segment {
// If path ends with //, fix it
if strings.HasSuffix(path, "//") {
path += "*"
}
var segments []segment
// Check for an absolute path
if strings.HasPrefix(path, "/") {
segments = append(segments, segment{new(selectRoot), []filter{}})
path = path[1:]
}
// Split path into segments
for _, s := range splitPath(path) {
segments = append(segments, c.parseSegment(s))
if c.err != ErrPath("") {
break
}
}
return segments
}
func splitPath(path string) []string {
var pieces []string
start := 0
inquote := false
for i := 0; i+1 <= len(path); i++ {
if path[i] == '\'' {
inquote = !inquote
} else if path[i] == '/' && !inquote {
pieces = append(pieces, path[start:i])
start = i + 1
}
}
return append(pieces, path[start:])
}
// parseSegment parses a path segment between / characters.
func (c *compiler) parseSegment(path string) segment {
pieces := strings.Split(path, "[")
seg := segment{
sel: c.parseSelector(pieces[0]),
filters: []filter{},
}
for i := 1; i < len(pieces); i++ {
fpath := pieces[i]
if len(fpath) == 0 || fpath[len(fpath)-1] != ']' {
c.err = ErrPath("path has invalid filter [brackets].")
break
}
seg.filters = append(seg.filters, c.parseFilter(fpath[:len(fpath)-1]))
}
return seg
}
// parseSelector parses a selector at the start of a path segment.
func (c *compiler) parseSelector(path string) selector {
switch path {
case ".":
return new(selectSelf)
case "..":
return new(selectParent)
case "*":
return new(selectChildren)
case "":
return new(selectDescendants)
default:
return newSelectChildrenByTag(path)
}
}
var fnTable = map[string]func(e *Element) string{
"local-name": (*Element).name,
"name": (*Element).FullTag,
"namespace-prefix": (*Element).namespacePrefix,
"namespace-uri": (*Element).NamespaceURI,
"text": (*Element).Text,
}
// parseFilter parses a path filter contained within [brackets].
func (c *compiler) parseFilter(path string) filter {
if len(path) == 0 {
c.err = ErrPath("path contains an empty filter expression.")
return nil
}
// Filter contains [@attr='val'], [fn()='val'], or [tag='val']?
eqindex := strings.Index(path, "='")
if eqindex >= 0 {
rindex := nextIndex(path, "'", eqindex+2)
if rindex != len(path)-1 {
c.err = ErrPath("path has mismatched filter quotes.")
return nil
}
key := path[:eqindex]
value := path[eqindex+2 : rindex]
switch {
case key[0] == '@':
return newFilterAttrVal(key[1:], value)
case strings.HasSuffix(key, "()"):
name := key[:len(key)-2]
if fn, ok := fnTable[name]; ok {
return newFilterFuncVal(fn, value)
}
c.err = ErrPath("path has unknown function " + name)
return nil
default:
return newFilterChildText(key, value)
}
}
// Filter contains [@attr], [N], [tag] or [fn()]
switch {
case path[0] == '@':
return newFilterAttr(path[1:])
case strings.HasSuffix(path, "()"):
name := path[:len(path)-2]
if fn, ok := fnTable[name]; ok {
return newFilterFunc(fn)
}
c.err = ErrPath("path has unknown function " + name)
return nil
case isInteger(path):
pos, _ := strconv.Atoi(path)
switch {
case pos > 0:
return newFilterPos(pos - 1)
default:
return newFilterPos(pos)
}
default:
return newFilterChild(path)
}
}
// selectSelf selects the current element into the candidate list.
type selectSelf struct{}
func (s *selectSelf) apply(e *Element, p *pather) {
p.candidates = append(p.candidates, e)
}
// selectRoot selects the element's root node.
type selectRoot struct{}
func (s *selectRoot) apply(e *Element, p *pather) {
root := e
for root.parent != nil {
root = root.parent
}
p.candidates = append(p.candidates, root)
}
// selectParent selects the element's parent into the candidate list.
type selectParent struct{}
func (s *selectParent) apply(e *Element, p *pather) {
if e.parent != nil {
p.candidates = append(p.candidates, e.parent)
}
}
// selectChildren selects the element's child elements into the
// candidate list.
type selectChildren struct{}
func (s *selectChildren) apply(e *Element, p *pather) {
for _, c := range e.Child {
if c, ok := c.(*Element); ok {
p.candidates = append(p.candidates, c)
}
}
}
// selectDescendants selects all descendant child elements
// of the element into the candidate list.
type selectDescendants struct{}
func (s *selectDescendants) apply(e *Element, p *pather) {
var queue fifo
for queue.add(e); queue.len() > 0; {
e := queue.remove().(*Element)
p.candidates = append(p.candidates, e)
for _, c := range e.Child {
if c, ok := c.(*Element); ok {
queue.add(c)
}
}
}
}
// selectChildrenByTag selects into the candidate list all child
// elements of the element having the specified tag.
type selectChildrenByTag struct {
space, tag string
}
func newSelectChildrenByTag(path string) *selectChildrenByTag {
s, l := spaceDecompose(path)
return &selectChildrenByTag{s, l}
}
func (s *selectChildrenByTag) apply(e *Element, p *pather) {
for _, c := range e.Child {
if c, ok := c.(*Element); ok && spaceMatch(s.space, c.Space) && s.tag == c.Tag {
p.candidates = append(p.candidates, c)
}
}
}
// filterPos filters the candidate list, keeping only the
// candidate at the specified index.
type filterPos struct {
index int
}
func newFilterPos(pos int) *filterPos {
return &filterPos{pos}
}
func (f *filterPos) apply(p *pather) {
if f.index >= 0 {
if f.index < len(p.candidates) {
p.scratch = append(p.scratch, p.candidates[f.index])
}
} else {
if -f.index <= len(p.candidates) {
p.scratch = append(p.scratch, p.candidates[len(p.candidates)+f.index])
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterAttr filters the candidate list for elements having
// the specified attribute.
type filterAttr struct {
space, key string
}
func newFilterAttr(str string) *filterAttr {
s, l := spaceDecompose(str)
return &filterAttr{s, l}
}
func (f *filterAttr) apply(p *pather) {
for _, c := range p.candidates {
for _, a := range c.Attr {
if spaceMatch(f.space, a.Space) && f.key == a.Key {
p.scratch = append(p.scratch, c)
break
}
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterAttrVal filters the candidate list for elements having
// the specified attribute with the specified value.
type filterAttrVal struct {
space, key, val string
}
func newFilterAttrVal(str, value string) *filterAttrVal {
s, l := spaceDecompose(str)
return &filterAttrVal{s, l, value}
}
func (f *filterAttrVal) apply(p *pather) {
for _, c := range p.candidates {
for _, a := range c.Attr {
if spaceMatch(f.space, a.Space) && f.key == a.Key && f.val == a.Value {
p.scratch = append(p.scratch, c)
break
}
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterFunc filters the candidate list for elements satisfying a custom
// boolean function.
type filterFunc struct {
fn func(e *Element) string
}
func newFilterFunc(fn func(e *Element) string) *filterFunc {
return &filterFunc{fn}
}
func (f *filterFunc) apply(p *pather) {
for _, c := range p.candidates {
if f.fn(c) != "" {
p.scratch = append(p.scratch, c)
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterFuncVal filters the candidate list for elements containing a value
// matching the result of a custom function.
type filterFuncVal struct {
fn func(e *Element) string
val string
}
func newFilterFuncVal(fn func(e *Element) string, value string) *filterFuncVal {
return &filterFuncVal{fn, value}
}
func (f *filterFuncVal) apply(p *pather) {
for _, c := range p.candidates {
if f.fn(c) == f.val {
p.scratch = append(p.scratch, c)
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterChild filters the candidate list for elements having
// a child element with the specified tag.
type filterChild struct {
space, tag string
}
func newFilterChild(str string) *filterChild {
s, l := spaceDecompose(str)
return &filterChild{s, l}
}
func (f *filterChild) apply(p *pather) {
for _, c := range p.candidates {
for _, cc := range c.Child {
if cc, ok := cc.(*Element); ok &&
spaceMatch(f.space, cc.Space) &&
f.tag == cc.Tag {
p.scratch = append(p.scratch, c)
}
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}
// filterChildText filters the candidate list for elements having
// a child element with the specified tag and text.
type filterChildText struct {
space, tag, text string
}
func newFilterChildText(str, text string) *filterChildText {
s, l := spaceDecompose(str)
return &filterChildText{s, l, text}
}
func (f *filterChildText) apply(p *pather) {
for _, c := range p.candidates {
for _, cc := range c.Child {
if cc, ok := cc.(*Element); ok &&
spaceMatch(f.space, cc.Space) &&
f.tag == cc.Tag &&
f.text == cc.Text() {
p.scratch = append(p.scratch, c)
}
}
}
p.candidates, p.scratch = p.scratch, p.candidates[0:0]
}

9
vendor/github.com/jackc/pgpassfile/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,9 @@
language: go
go:
- 1.x
- tip
matrix:
allow_failures:
- go: tip

22
vendor/github.com/jackc/pgpassfile/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2019 Jack Christensen
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

8
vendor/github.com/jackc/pgpassfile/README.md generated vendored Normal file
View File

@ -0,0 +1,8 @@
[![](https://godoc.org/github.com/jackc/pgpassfile?status.svg)](https://godoc.org/github.com/jackc/pgpassfile)
[![Build Status](https://travis-ci.org/jackc/pgpassfile.svg)](https://travis-ci.org/jackc/pgpassfile)
# pgpassfile
Package pgpassfile is a parser PostgreSQL .pgpass files.
Extracted and rewritten from original implementation in https://github.com/jackc/pgx.

110
vendor/github.com/jackc/pgpassfile/pgpass.go generated vendored Normal file
View File

@ -0,0 +1,110 @@
// Package pgpassfile is a parser PostgreSQL .pgpass files.
package pgpassfile
import (
"bufio"
"io"
"os"
"regexp"
"strings"
)
// Entry represents a line in a PG passfile.
type Entry struct {
Hostname string
Port string
Database string
Username string
Password string
}
// Passfile is the in memory data structure representing a PG passfile.
type Passfile struct {
Entries []*Entry
}
// ReadPassfile reads the file at path and parses it into a Passfile.
func ReadPassfile(path string) (*Passfile, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ParsePassfile(f)
}
// ParsePassfile reads r and parses it into a Passfile.
func ParsePassfile(r io.Reader) (*Passfile, error) {
passfile := &Passfile{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
entry := parseLine(scanner.Text())
if entry != nil {
passfile.Entries = append(passfile.Entries, entry)
}
}
return passfile, scanner.Err()
}
// Match (not colons or escaped colon or escaped backslash)+. Essentially gives a split on unescaped
// colon.
var colonSplitterRegexp = regexp.MustCompile("(([^:]|(\\:)))+")
// var colonSplitterRegexp = regexp.MustCompile("((?:[^:]|(?:\\:)|(?:\\\\))+)")
// parseLine parses a line into an *Entry. It returns nil on comment lines or any other unparsable
// line.
func parseLine(line string) *Entry {
const (
tmpBackslash = "\r"
tmpColon = "\n"
)
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") {
return nil
}
line = strings.Replace(line, `\\`, tmpBackslash, -1)
line = strings.Replace(line, `\:`, tmpColon, -1)
parts := strings.Split(line, ":")
if len(parts) != 5 {
return nil
}
// Unescape escaped colons and backslashes
for i := range parts {
parts[i] = strings.Replace(parts[i], tmpBackslash, `\`, -1)
parts[i] = strings.Replace(parts[i], tmpColon, `:`, -1)
}
return &Entry{
Hostname: parts[0],
Port: parts[1],
Database: parts[2],
Username: parts[3],
Password: parts[4],
}
}
// FindPassword finds the password for the provided hostname, port, database, and username. For a
// Unix domain socket hostname must be set to "localhost". An empty string will be returned if no
// match is found.
//
// See https://www.postgresql.org/docs/current/libpq-pgpass.html for more password file information.
func (pf *Passfile) FindPassword(hostname, port, database, username string) (password string) {
for _, e := range pf.Entries {
if (e.Hostname == "*" || e.Hostname == hostname) &&
(e.Port == "*" || e.Port == port) &&
(e.Database == "*" || e.Database == database) &&
(e.Username == "*" || e.Username == username) {
return e.Password
}
}
return ""
}

9
vendor/github.com/jackc/pgservicefile/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,9 @@
language: go
go:
- 1.x
- tip
matrix:
allow_failures:
- go: tip

22
vendor/github.com/jackc/pgservicefile/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2020 Jack Christensen
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

6
vendor/github.com/jackc/pgservicefile/README.md generated vendored Normal file
View File

@ -0,0 +1,6 @@
[![](https://godoc.org/github.com/jackc/pgservicefile?status.svg)](https://godoc.org/github.com/jackc/pgservicefile)
[![Build Status](https://travis-ci.org/jackc/pgservicefile.svg)](https://travis-ci.org/jackc/pgservicefile)
# pgservicefile
Package pgservicefile is a parser for PostgreSQL service files (e.g. `.pg_service.conf`).

79
vendor/github.com/jackc/pgservicefile/pgservicefile.go generated vendored Normal file
View File

@ -0,0 +1,79 @@
// Package pgservicefile is a parser for PostgreSQL service files (e.g. .pg_service.conf).
package pgservicefile
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
)
type Service struct {
Name string
Settings map[string]string
}
type Servicefile struct {
Services []*Service
servicesByName map[string]*Service
}
// GetService returns the named service.
func (sf *Servicefile) GetService(name string) (*Service, error) {
service, present := sf.servicesByName[name]
if !present {
return nil, errors.New("not found")
}
return service, nil
}
// ReadServicefile reads the file at path and parses it into a Servicefile.
func ReadServicefile(path string) (*Servicefile, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ParseServicefile(f)
}
// ParseServicefile reads r and parses it into a Servicefile.
func ParseServicefile(r io.Reader) (*Servicefile, error) {
servicefile := &Servicefile{}
var service *Service
scanner := bufio.NewScanner(r)
lineNum := 0
for scanner.Scan() {
lineNum += 1
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
// ignore comments and empty lines
} else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
service = &Service{Name: line[1 : len(line)-1], Settings: make(map[string]string)}
servicefile.Services = append(servicefile.Services, service)
} else {
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("unable to parse line %d", lineNum)
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
service.Settings[key] = value
}
}
servicefile.servicesByName = make(map[string]*Service, len(servicefile.Services))
for _, service := range servicefile.Services {
servicefile.servicesByName[service.Name] = service
}
return servicefile, scanner.Err()
}

27
vendor/github.com/jackc/pgx/v5/.gitignore generated vendored Normal file
View File

@ -0,0 +1,27 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
.envrc
/.testdb
.DS_Store

311
vendor/github.com/jackc/pgx/v5/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,311 @@
# 5.4.3 (August 5, 2023)
* Fix: QCharArrayOID was defined with the wrong OID (Christoph Engelbert)
* Fix: connect_timeout for sslmode=allow|prefer (smaher-edb)
* Fix: pgxpool: background health check cannot overflow pool
* Fix: Check for nil in defer when sending batch (recover properly from panic)
* Fix: json scan of non-string pointer to pointer
* Fix: zeronull.Timestamptz should use pgtype.Timestamptz
* Fix: NewConnsCount was not correctly counting connections created by Acquire directly. (James Hartig)
* RowTo(AddrOf)StructByPos ignores fields with "-" db tag
* Optimization: improve text format numeric parsing (horpto)
# 5.4.2 (July 11, 2023)
* Fix: RowScanner errors are fatal to Rows
* Fix: Enable failover efforts when pg_hba.conf disallows non-ssl connections (Brandon Kauffman)
* Hstore text codec internal improvements (Evan Jones)
* Fix: Stop timers for background reader when not in use. Fixes memory leak when closing connections (Adrian-Stefan Mares)
* Fix: Stop background reader as soon as possible.
* Add PgConn.SyncConn(). This combined with the above fix makes it safe to directly use the underlying net.Conn.
# 5.4.1 (June 18, 2023)
* Fix: concurrency bug with pgtypeDefaultMap and simple protocol (Lev Zakharov)
* Add TxOptions.BeginQuery to allow overriding the default BEGIN query
# 5.4.0 (June 14, 2023)
* Replace platform specific syscalls for non-blocking IO with more traditional goroutines and deadlines. This returns to the v4 approach with some additional improvements and fixes. This restores the ability to use a pgx.Conn over an ssh.Conn as well as other non-TCP or Unix socket connections. In addition, it is a significantly simpler implementation that is less likely to have cross platform issues.
* Optimization: The default type registrations are now shared among all connections. This saves about 100KB of memory per connection. `pgtype.Type` and `pgtype.Codec` values are now required to be immutable after registration. This was already necessary in most cases but wasn't documented until now. (Lev Zakharov)
* Fix: Ensure pgxpool.Pool.QueryRow.Scan releases connection on panic
* CancelRequest: don't try to read the reply (Nicola Murino)
* Fix: correctly handle bool type aliases (Wichert Akkerman)
* Fix: pgconn.CancelRequest: Fix unix sockets: don't use RemoteAddr()
* Fix: pgx.Conn memory leak with prepared statement caching (Evan Jones)
* Add BeforeClose to pgxpool.Pool (Evan Cordell)
* Fix: various hstore fixes and optimizations (Evan Jones)
* Fix: RowToStructByPos with embedded unexported struct
* Support different bool string representations (Lev Zakharov)
* Fix: error when using BatchResults.Exec on a select that returns an error after some rows.
* Fix: pipelineBatchResults.Exec() not returning error from ResultReader
* Fix: pipeline batch results not closing pipeline when error occurs while reading directly from results instead of using
a callback.
* Fix: scanning a table type into a struct
* Fix: scan array of record to pointer to slice of struct
* Fix: handle null for json (Cemre Mengu)
* Batch Query callback is called even when there is an error
* Add RowTo(AddrOf)StructByNameLax (Audi P. Risa P)
# 5.3.1 (February 27, 2023)
* Fix: Support v4 and v5 stdlib in same program (Tomáš Procházka)
* Fix: sql.Scanner not being used in certain cases
* Add text format jsonpath support
* Fix: fake non-blocking read adaptive wait time
# 5.3.0 (February 11, 2023)
* Fix: json values work with sql.Scanner
* Fixed / improved error messages (Mark Chambers and Yevgeny Pats)
* Fix: support scan into single dimensional arrays
* Fix: MaxConnLifetimeJitter setting actually jitter (Ben Weintraub)
* Fix: driver.Value representation of bytea should be []byte not string
* Fix: better handling of unregistered OIDs
* CopyFrom can use query cache to avoid extra round trip to get OIDs (Alejandro Do Nascimento Mora)
* Fix: encode to json ignoring driver.Valuer
* Support sql.Scanner on renamed base type
* Fix: pgtype.Numeric text encoding of negative numbers (Mark Chambers)
* Fix: connect with multiple hostnames when one can't be resolved
* Upgrade puddle to remove dependency on uber/atomic and fix alignment issue on 32-bit platform
* Fix: scanning json column into **string
* Multiple reductions in memory allocations
* Fake non-blocking read adapts its max wait time
* Improve CopyFrom performance and reduce memory usage
* Fix: encode []any to array
* Fix: LoadType for composite with dropped attributes (Felix Röhrich)
* Support v4 and v5 stdlib in same program
* Fix: text format array decoding with string of "NULL"
* Prefer binary format for arrays
# 5.2.0 (December 5, 2022)
* `tracelog.TraceLog` implements the pgx.PrepareTracer interface. (Vitalii Solodilov)
* Optimize creating begin transaction SQL string (Petr Evdokimov and ksco)
* `Conn.LoadType` supports range and multirange types (Vitalii Solodilov)
* Fix scan `uint` and `uint64` `ScanNumeric`. This resolves a PostgreSQL `numeric` being incorrectly scanned into `uint` and `uint64`.
# 5.1.1 (November 17, 2022)
* Fix simple query sanitizer where query text contains a Unicode replacement character.
* Remove erroneous `name` argument from `DeallocateAll()`. Technically, this is a breaking change, but given that method was only added 5 days ago this change was accepted. (Bodo Kaiser)
# 5.1.0 (November 12, 2022)
* Update puddle to v2.1.2. This resolves a race condition and a deadlock in pgxpool.
* `QueryRewriter.RewriteQuery` now returns an error. Technically, this is a breaking change for any external implementers, but given the minimal likelihood that there are actually any external implementers this change was accepted.
* Expose `GetSSLPassword` support to pgx.
* Fix encode `ErrorResponse` unknown field handling. This would only affect pgproto3 being used directly as a proxy with a non-PostgreSQL server that included additional error fields.
* Fix date text format encoding with 5 digit years.
* Fix date values passed to a `sql.Scanner` as `string` instead of `time.Time`.
* DateCodec.DecodeValue can return `pgtype.InfinityModifier` instead of `string` for infinite values. This now matches the behavior of the timestamp types.
* Add domain type support to `Conn.LoadType()`.
* Add `RowToStructByName` and `RowToAddrOfStructByName`. (Pavlo Golub)
* Add `Conn.DeallocateAll()` to clear all prepared statements including the statement cache. (Bodo Kaiser)
# 5.0.4 (October 24, 2022)
* Fix: CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows
* Fix: some reflect Kind checks to first check for nil
* Bump golang.org/x/text dependency to placate snyk
* Fix: RowToStructByPos on structs with multiple anonymous sub-structs (Baptiste Fontaine)
* Fix: Exec checks if tx is closed
# 5.0.3 (October 14, 2022)
* Fix `driver.Valuer` handling edge cases that could cause infinite loop or crash
# v5.0.2 (October 8, 2022)
* Fix date encoding in text format to always use 2 digits for month and day
* Prefer driver.Valuer over wrap plans when encoding
* Fix scan to pointer to pointer to renamed type
* Allow scanning NULL even if PG and Go types are incompatible
# v5.0.1 (September 24, 2022)
* Fix 32-bit atomic usage
* Add MarshalJSON for Float8 (yogipristiawan)
* Add `[` and `]` to text encoding of `Lseg`
* Fix sqlScannerWrapper NULL handling
# v5.0.0 (September 17, 2022)
## Merged Packages
`github.com/jackc/pgtype`, `github.com/jackc/pgconn`, and `github.com/jackc/pgproto3` are now included in the main
`github.com/jackc/pgx` repository. Previously there was confusion as to where issues should be reported, additional
release work due to releasing multiple packages, and less clear changelogs.
## pgconn
`CommandTag` is now an opaque type instead of directly exposing an underlying `[]byte`.
The return value `ResultReader.Values()` is no longer safe to retain a reference to after a subsequent call to `NextRow()` or `Close()`.
`Trace()` method adds low level message tracing similar to the `PQtrace` function in `libpq`.
pgconn now uses non-blocking IO. This is a significant internal restructuring, but it should not cause any visible changes on its own. However, it is important in implementing other new features.
`CheckConn()` checks a connection's liveness by doing a non-blocking read. This can be used to detect database restarts or network interruptions without executing a query or a ping.
pgconn now supports pipeline mode.
`*PgConn.ReceiveResults` removed. Use pipeline mode instead.
`Timeout()` no longer considers `context.Canceled` as a timeout error. `context.DeadlineExceeded` still is considered a timeout error.
## pgxpool
`Connect` and `ConnectConfig` have been renamed to `New` and `NewWithConfig` respectively. The `LazyConnect` option has been removed. Pools always lazily connect.
## pgtype
The `pgtype` package has been significantly changed.
### NULL Representation
Previously, types had a `Status` field that could be `Undefined`, `Null`, or `Present`. This has been changed to a
`Valid` `bool` field to harmonize with how `database/sql` represents `NULL` and to make the zero value useable.
Previously, a type that implemented `driver.Valuer` would have the `Value` method called even on a nil pointer. All nils
whether typed or untyped now represent `NULL`.
### Codec and Value Split
Previously, the type system combined decoding and encoding values with the value types. e.g. Type `Int8` both handled
encoding and decoding the PostgreSQL representation and acted as a value object. This caused some difficulties when
there was not an exact 1 to 1 relationship between the Go types and the PostgreSQL types For example, scanning a
PostgreSQL binary `numeric` into a Go `float64` was awkward (see https://github.com/jackc/pgtype/issues/147). This
concepts have been separated. A `Codec` only has responsibility for encoding and decoding values. Value types are
generally defined by implementing an interface that a particular `Codec` understands (e.g. `PointScanner` and
`PointValuer` for the PostgreSQL `point` type).
### Array Types
All array types are now handled by `ArrayCodec` instead of using code generation for each new array type. This also
means that less common array types such as `point[]` are now supported. `Array[T]` supports PostgreSQL multi-dimensional
arrays.
### Composite Types
Composite types must be registered before use. `CompositeFields` may still be used to construct and destruct composite
values, but any type may now implement `CompositeIndexGetter` and `CompositeIndexScanner` to be used as a composite.
### Range Types
Range types are now handled with types `RangeCodec` and `Range[T]`. This allows additional user defined range types to
easily be handled. Multirange types are handled similarly with `MultirangeCodec` and `Multirange[T]`.
### pgxtype
`LoadDataType` moved to `*Conn` as `LoadType`.
### Bytea
The `Bytea` and `GenericBinary` types have been replaced. Use the following instead:
* `[]byte` - For normal usage directly use `[]byte`.
* `DriverBytes` - Uses driver memory only available until next database method call. Avoids a copy and an allocation.
* `PreallocBytes` - Uses preallocated byte slice to avoid an allocation.
* `UndecodedBytes` - Avoids any decoding. Allows working with raw bytes.
### Dropped lib/pq Support
`pgtype` previously supported and was tested against [lib/pq](https://github.com/lib/pq). While it will continue to work
in most cases this is no longer supported.
### database/sql Scan
Previously, most `Scan` implementations would convert `[]byte` to `string` automatically to decode a text value. Now
only `string` is handled. This is to allow the possibility of future binary support in `database/sql` mode by
considering `[]byte` to be binary format and `string` text format. This change should have no effect for any use with
`pgx`. The previous behavior was only necessary for `lib/pq` compatibility.
Added `*Map.SQLScanner` to create a `sql.Scanner` for types such as `[]int32` and `Range[T]` that do not implement
`sql.Scanner` directly.
### Number Type Fields Include Bit size
`Int2`, `Int4`, `Int8`, `Float4`, `Float8`, and `Uint32` fields now include bit size. e.g. `Int` is renamed to `Int64`.
This matches the convention set by `database/sql`. In addition, for comparable types like `pgtype.Int8` and
`sql.NullInt64` the structures are identical. This means they can be directly converted one to another.
### 3rd Party Type Integrations
* Extracted integrations with https://github.com/shopspring/decimal and https://github.com/gofrs/uuid to
https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid respectively. This trims
the pgx dependency tree.
### Other Changes
* `Bit` and `Varbit` are both replaced by the `Bits` type.
* `CID`, `OID`, `OIDValue`, and `XID` are replaced by the `Uint32` type.
* `Hstore` is now defined as `map[string]*string`.
* `JSON` and `JSONB` types removed. Use `[]byte` or `string` directly.
* `QChar` type removed. Use `rune` or `byte` directly.
* `Inet` and `Cidr` types removed. Use `netip.Addr` and `netip.Prefix` directly. These types are more memory efficient than the previous `net.IPNet`.
* `Macaddr` type removed. Use `net.HardwareAddr` directly.
* Renamed `pgtype.ConnInfo` to `pgtype.Map`.
* Renamed `pgtype.DataType` to `pgtype.Type`.
* Renamed `pgtype.None` to `pgtype.Finite`.
* `RegisterType` now accepts a `*Type` instead of `Type`.
* Assorted array helper methods and types made private.
## stdlib
* Removed `AcquireConn` and `ReleaseConn` as that functionality has been built in since Go 1.13.
## Reduced Memory Usage by Reusing Read Buffers
Previously, the connection read buffer would allocate large chunks of memory and never reuse them. This allowed
transferring ownership to anything such as scanned values without incurring an additional allocation and memory copy.
However, this came at the cost of overall increased memory allocation size. But worse it was also possible to pin large
chunks of memory by retaining a reference to a small value that originally came directly from the read buffer. Now
ownership remains with the read buffer and anything needing to retain a value must make a copy.
## Query Execution Modes
Control over automatic prepared statement caching and simple protocol use are now combined into query execution mode.
See documentation for `QueryExecMode`.
## QueryRewriter Interface and NamedArgs
pgx now supports named arguments with the `NamedArgs` type. This is implemented via the new `QueryRewriter` interface which
allows arbitrary rewriting of query SQL and arguments.
## RowScanner Interface
The `RowScanner` interface allows a single argument to Rows.Scan to scan the entire row.
## Rows Result Helpers
* `CollectRows` and `RowTo*` functions simplify collecting results into a slice.
* `CollectOneRow` collects one row using `RowTo*` functions.
* `ForEachRow` simplifies scanning each row and executing code using the scanned values. `ForEachRow` replaces `QueryFunc`.
## Tx Helpers
Rather than every type that implemented `Begin` or `BeginTx` methods also needing to implement `BeginFunc` and
`BeginTxFunc` these methods have been converted to functions that take a db that implements `Begin` or `BeginTx`.
## Improved Batch Query Ergonomics
Previously, the code for building a batch went in one place before the call to `SendBatch`, and the code for reading the
results went in one place after the call to `SendBatch`. This could make it difficult to match up the query and the code
to handle the results. Now `Queue` returns a `QueuedQuery` which has methods `Query`, `QueryRow`, and `Exec` which can
be used to register a callback function that will handle the result. Callback functions are called automatically when
`BatchResults.Close` is called.
## SendBatch Uses Pipeline Mode When Appropriate
Previously, a batch with 10 unique parameterized statements executed 100 times would entail 11 network round trips. 1
for each prepare / describe and 1 for executing them all. Now pipeline mode is used to prepare / describe all statements
in a single network round trip. So it would only take 2 round trips.
## Tracing and Logging
Internal logging support has been replaced with tracing hooks. This allows custom tracing integration with tools like OpenTelemetry. Package tracelog provides an adapter for pgx v4 loggers to act as a tracer.
All integrations with 3rd party loggers have been extracted to separate repositories. This trims the pgx dependency
tree.

134
vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md generated vendored Normal file
View File

@ -0,0 +1,134 @@
# Contributing
## Discuss Significant Changes
Before you invest a significant amount of time on a change, please create a discussion or issue describing your
proposal. This will help to ensure your proposed change has a reasonable chance of being merged.
## Avoid Dependencies
Adding a dependency is a big deal. While on occasion a new dependency may be accepted, the default answer to any change
that adds a dependency is no.
## Development Environment Setup
pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE`
environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition,
the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to
simplify environment variable handling.
### Using an Existing PostgreSQL Cluster
If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx
test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different
authentication methods).
Create and setup a test database:
```
export PGDATABASE=pgx_test
createdb
psql -c 'create extension hstore;'
psql -c 'create domain uint64 as numeric(20,0);'
```
Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods
such as Homebrew do not.
```
createuser -s postgres
```
Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests.
```
export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test"
go test ./...
```
This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods).
### Creating a New PostgreSQL Cluster Exclusively for Testing
The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is
highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`.
```
export PGPORT=5015
export PGUSER=postgres
export PGDATABASE=pgx_test
export POSTGRESQL_DATA_DIR=postgresql
export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test"
export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test"
export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret"
export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem"
export PGX_SSL_PASSWORD=certpw
export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key"
```
Create a new database cluster.
```
initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR
echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf
cp testsetup/ca.cnf .testdb
cp testsetup/localhost.cnf .testdb
cp testsetup/pgx_sslcert.cnf .testdb
cd .testdb
# Generate a CA public / private key pair.
openssl genrsa -out ca.key 4096
openssl req -x509 -config ca.cnf -new -nodes -key ca.key -sha256 -days 365 -subj '/O=pgx-test-root' -out ca.pem
# Generate the certificate for localhost (the server).
openssl genrsa -out localhost.key 2048
openssl req -new -config localhost.cnf -key localhost.key -out localhost.csr
openssl x509 -req -in localhost.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out localhost.crt -days 364 -sha256 -extfile localhost.cnf -extensions v3_req
# Copy certificates to server directory and set permissions.
cp ca.pem $POSTGRESQL_DATA_DIR/root.crt
cp localhost.key $POSTGRESQL_DATA_DIR/server.key
chmod 600 $POSTGRESQL_DATA_DIR/server.key
cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt
# Generate the certificate for client authentication.
openssl genrsa -des3 -out pgx_sslcert.key -passout pass:certpw 2048
openssl req -new -config pgx_sslcert.cnf -key pgx_sslcert.key -passin pass:certpw -out pgx_sslcert.csr
openssl x509 -req -in pgx_sslcert.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out pgx_sslcert.crt -days 363 -sha256 -extfile pgx_sslcert.cnf -extensions v3_req
cd ..
```
Start the new cluster. This will be necessary whenever you are running pgx tests.
```
postgres -D .testdb/$POSTGRESQL_DATA_DIR
```
Setup the test database in the new cluster.
```
createdb
psql --no-psqlrc -f testsetup/postgresql_setup.sql
```
### PgBouncer
There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set.
### Optional Tests
pgx supports multiple connection types and means of authentication. These tests are optional. They will only run if the
appropriate environment variables are set. In addition, there may be tests specific to particular PostgreSQL versions,
non-PostgreSQL servers (e.g. CockroachDB), or connection poolers (e.g. PgBouncer). `go test ./... -v | grep SKIP` to see
if any tests are being skipped.

22
vendor/github.com/jackc/pgx/v5/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2013-2021 Jack Christensen
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

169
vendor/github.com/jackc/pgx/v5/README.md generated vendored Normal file
View File

@ -0,0 +1,169 @@
[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgx/v5.svg)](https://pkg.go.dev/github.com/jackc/pgx/v5)
[![Build Status](https://github.com/jackc/pgx/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgx/actions/workflows/ci.yml)
# pgx - PostgreSQL Driver and Toolkit
pgx is a pure Go driver and toolkit for PostgreSQL.
The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as `LISTEN` /
`NOTIFY` and `COPY`. It also includes an adapter for the standard `database/sql` interface.
The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol
and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers,
proxies, load balancers, logical replication clients, etc.
## Example Usage
```go
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
)
func main() {
// urlExample := "postgres://username:password@localhost:5432/database_name"
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
var name string
var weight int64
err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
if err != nil {
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
os.Exit(1)
}
fmt.Println(name, weight)
}
```
See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information.
## Features
* Support for approximately 70 different PostgreSQL types
* Automatic statement preparation and caching
* Batch queries
* Single-round trip query mode
* Full TLS connection control
* Binary format support for custom types (allows for much quicker encoding/decoding)
* `COPY` protocol support for faster bulk data loads
* Tracing and logging support
* Connection pool with after-connect hook for arbitrary connection setup
* `LISTEN` / `NOTIFY`
* Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings
* `hstore` support
* `json` and `jsonb` support
* Maps `inet` and `cidr` PostgreSQL types to `netip.Addr` and `netip.Prefix`
* Large object support
* NULL mapping to pointer to pointer
* Supports `database/sql.Scanner` and `database/sql/driver.Valuer` interfaces for custom types
* Notice response handling
* Simulated nested transactions with savepoints
## Choosing Between the pgx and database/sql Interfaces
The pgx interface is faster. Many PostgreSQL specific features such as `LISTEN` / `NOTIFY` and `COPY` are not available
through the `database/sql` interface.
The pgx interface is recommended when:
1. The application only targets PostgreSQL.
2. No other libraries that require `database/sql` are in use.
It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed.
## Testing
See CONTRIBUTING.md for setup instructions.
## Supported Go and PostgreSQL Versions
pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.19 and higher and PostgreSQL 11 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/).
## Version Policy
pgx follows semantic versioning for the documented public API on stable releases. `v5` is the latest stable major version.
## PGX Family Libraries
### [github.com/jackc/pglogrepl](https://github.com/jackc/pglogrepl)
pglogrepl provides functionality to act as a client for PostgreSQL logical replication.
### [github.com/jackc/pgmock](https://github.com/jackc/pgmock)
pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler).
### [github.com/jackc/tern](https://github.com/jackc/tern)
tern is a stand-alone SQL migration system.
### [github.com/jackc/pgerrcode](https://github.com/jackc/pgerrcode)
pgerrcode contains constants for the PostgreSQL error codes.
## Adapters for 3rd Party Types
* [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid)
* [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal)
* [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid)
## Adapters for 3rd Party Tracers
* [https://github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer)
## Adapters for 3rd Party Loggers
These adapters can be used with the tracelog package.
* [github.com/jackc/pgx-go-kit-log](https://github.com/jackc/pgx-go-kit-log)
* [github.com/jackc/pgx-log15](https://github.com/jackc/pgx-log15)
* [github.com/jackc/pgx-logrus](https://github.com/jackc/pgx-logrus)
* [github.com/jackc/pgx-zap](https://github.com/jackc/pgx-zap)
* [github.com/jackc/pgx-zerolog](https://github.com/jackc/pgx-zerolog)
* [github.com/mcosta74/pgx-slog](https://github.com/mcosta74/pgx-slog)
* [github.com/kataras/pgx-golog](https://github.com/kataras/pgx-golog)
## 3rd Party Libraries with PGX Support
### [github.com/pashagolub/pgxmock](https://github.com/pashagolub/pgxmock)
pgxmock is a mock library implementing pgx interfaces.
pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection.
### [github.com/georgysavva/scany](https://github.com/georgysavva/scany)
Library for scanning data from a database into Go structs and more.
### [github.com/vingarcia/ksql](https://github.com/vingarcia/ksql)
A carefully designed SQL client for making using SQL easier,
more productive, and less error-prone on Golang.
### [https://github.com/otan/gopgkrb5](https://github.com/otan/gopgkrb5)
Adds GSSAPI / Kerberos authentication support.
### [github.com/wcamarao/pmx](https://github.com/wcamarao/pmx)
Explicit data mapping and scanning library for Go structs and slices.
### [github.com/stephenafamo/scan](https://github.com/stephenafamo/scan)
Type safe and flexible package for scanning database data into Go types.
Supports, structs, maps, slices and custom mapping functions.
### [https://github.com/z0ne-dev/mgx](https://github.com/z0ne-dev/mgx)
Code first migration library for native pgx (no database/sql abstraction).

18
vendor/github.com/jackc/pgx/v5/Rakefile generated vendored Normal file
View File

@ -0,0 +1,18 @@
require "erb"
rule '.go' => '.go.erb' do |task|
erb = ERB.new(File.read(task.source))
File.write(task.name, "// Do not edit. Generated from #{task.source}\n" + erb.result(binding))
sh "goimports", "-w", task.name
end
generated_code_files = [
"pgtype/int.go",
"pgtype/int_test.go",
"pgtype/integration_benchmark_test.go",
"pgtype/zeronull/int.go",
"pgtype/zeronull/int_test.go"
]
desc "Generate code"
task generate: generated_code_files

431
vendor/github.com/jackc/pgx/v5/batch.go generated vendored Normal file
View File

@ -0,0 +1,431 @@
package pgx
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgconn"
)
// QueuedQuery is a query that has been queued for execution via a Batch.
type QueuedQuery struct {
query string
arguments []any
fn batchItemFunc
sd *pgconn.StatementDescription
}
type batchItemFunc func(br BatchResults) error
// Query sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) Query(fn func(rows Rows) error) {
qq.fn = func(br BatchResults) error {
rows, _ := br.Query()
defer rows.Close()
err := fn(rows)
if err != nil {
return err
}
rows.Close()
return rows.Err()
}
}
// Query sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) QueryRow(fn func(row Row) error) {
qq.fn = func(br BatchResults) error {
row := br.QueryRow()
return fn(row)
}
}
// Exec sets fn to be called when the response to qq is received.
func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) {
qq.fn = func(br BatchResults) error {
ct, err := br.Exec()
if err != nil {
return err
}
return fn(ct)
}
}
// Batch queries are a way of bundling multiple queries together to avoid
// unnecessary network round trips. A Batch must only be sent once.
type Batch struct {
queuedQueries []*QueuedQuery
}
// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement.
func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery {
qq := &QueuedQuery{
query: query,
arguments: arguments,
}
b.queuedQueries = append(b.queuedQueries, qq)
return qq
}
// Len returns number of queries that have been queued so far.
func (b *Batch) Len() int {
return len(b.queuedQueries)
}
type BatchResults interface {
// Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer
// calling Exec on the QueuedQuery.
Exec() (pgconn.CommandTag, error)
// Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer
// calling Query on the QueuedQuery.
Query() (Rows, error)
// QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow.
// Prefer calling QueryRow on the QueuedQuery.
QueryRow() Row
// Close closes the batch operation. All unread results are read and any callback functions registered with
// QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an
// error or the batch encounters an error subsequent callback functions will not be called.
//
// Close must be called before the underlying connection can be used again. Any error that occurred during a batch
// operation may have made it impossible to resyncronize the connection with the server. In this case the underlying
// connection will have been closed.
//
// Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback
// functions will not be rerun.
Close() error
}
type batchResults struct {
ctx context.Context
conn *Conn
mrr *pgconn.MultiResultReader
err error
b *Batch
qqIdx int
closed bool
endTraced bool
}
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
func (br *batchResults) Exec() (pgconn.CommandTag, error) {
if br.err != nil {
return pgconn.CommandTag{}, br.err
}
if br.closed {
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
}
query, arguments, _ := br.nextQueryAndArgs()
if !br.mrr.NextResult() {
err := br.mrr.Close()
if err == nil {
err = errors.New("no result")
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: err,
})
}
return pgconn.CommandTag{}, err
}
commandTag, err := br.mrr.ResultReader().Close()
if err != nil {
br.err = err
br.mrr.Close()
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
CommandTag: commandTag,
Err: br.err,
})
}
return commandTag, br.err
}
// Query reads the results from the next query in the batch as if the query has been sent with Query.
func (br *batchResults) Query() (Rows, error) {
query, arguments, ok := br.nextQueryAndArgs()
if !ok {
query = "batch query"
}
if br.err != nil {
return &baseRows{err: br.err, closed: true}, br.err
}
if br.closed {
alreadyClosedErr := fmt.Errorf("batch already closed")
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
}
rows := br.conn.getRows(br.ctx, query, arguments)
rows.batchTracer = br.conn.batchTracer
if !br.mrr.NextResult() {
rows.err = br.mrr.Close()
if rows.err == nil {
rows.err = errors.New("no result")
}
rows.closed = true
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: rows.err,
})
}
return rows, rows.err
}
rows.resultReader = br.mrr.ResultReader()
return rows, nil
}
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
func (br *batchResults) QueryRow() Row {
rows, _ := br.Query()
return (*connRow)(rows.(*baseRows))
}
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
func (br *batchResults) Close() error {
defer func() {
if !br.endTraced {
if br.conn != nil && br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
}
br.endTraced = true
}
}()
if br.err != nil {
return br.err
}
if br.closed {
return nil
}
// Read and run fn for all remaining items
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.queuedQueries) {
if br.b.queuedQueries[br.qqIdx].fn != nil {
err := br.b.queuedQueries[br.qqIdx].fn(br)
if err != nil {
br.err = err
}
} else {
br.Exec()
}
}
br.closed = true
err := br.mrr.Close()
if br.err == nil {
br.err = err
}
return br.err
}
func (br *batchResults) earlyError() error {
return br.err
}
func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) {
if br.b != nil && br.qqIdx < len(br.b.queuedQueries) {
bi := br.b.queuedQueries[br.qqIdx]
query = bi.query
args = bi.arguments
ok = true
br.qqIdx++
}
return
}
type pipelineBatchResults struct {
ctx context.Context
conn *Conn
pipeline *pgconn.Pipeline
lastRows *baseRows
err error
b *Batch
qqIdx int
closed bool
endTraced bool
}
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
if br.err != nil {
return pgconn.CommandTag{}, br.err
}
if br.closed {
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
}
if br.lastRows != nil && br.lastRows.err != nil {
return pgconn.CommandTag{}, br.err
}
query, arguments, _ := br.nextQueryAndArgs()
results, err := br.pipeline.GetResults()
if err != nil {
br.err = err
return pgconn.CommandTag{}, br.err
}
var commandTag pgconn.CommandTag
switch results := results.(type) {
case *pgconn.ResultReader:
commandTag, br.err = results.Close()
default:
return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results)
}
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
CommandTag: commandTag,
Err: br.err,
})
}
return commandTag, br.err
}
// Query reads the results from the next query in the batch as if the query has been sent with Query.
func (br *pipelineBatchResults) Query() (Rows, error) {
if br.err != nil {
return &baseRows{err: br.err, closed: true}, br.err
}
if br.closed {
alreadyClosedErr := fmt.Errorf("batch already closed")
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
}
if br.lastRows != nil && br.lastRows.err != nil {
br.err = br.lastRows.err
return &baseRows{err: br.err, closed: true}, br.err
}
query, arguments, ok := br.nextQueryAndArgs()
if !ok {
query = "batch query"
}
rows := br.conn.getRows(br.ctx, query, arguments)
rows.batchTracer = br.conn.batchTracer
br.lastRows = rows
results, err := br.pipeline.GetResults()
if err != nil {
br.err = err
rows.err = err
rows.closed = true
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
SQL: query,
Args: arguments,
Err: err,
})
}
} else {
switch results := results.(type) {
case *pgconn.ResultReader:
rows.resultReader = results
default:
err = fmt.Errorf("unexpected pipeline result: %T", results)
br.err = err
rows.err = err
rows.closed = true
}
}
return rows, rows.err
}
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
func (br *pipelineBatchResults) QueryRow() Row {
rows, _ := br.Query()
return (*connRow)(rows.(*baseRows))
}
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
func (br *pipelineBatchResults) Close() error {
defer func() {
if !br.endTraced {
if br.conn.batchTracer != nil {
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
}
br.endTraced = true
}
}()
if br.err == nil && br.lastRows != nil && br.lastRows.err != nil {
br.err = br.lastRows.err
return br.err
}
if br.closed {
return br.err
}
// Read and run fn for all remaining items
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.queuedQueries) {
if br.b.queuedQueries[br.qqIdx].fn != nil {
err := br.b.queuedQueries[br.qqIdx].fn(br)
if err != nil {
br.err = err
}
} else {
br.Exec()
}
}
br.closed = true
err := br.pipeline.Close()
if br.err == nil {
br.err = err
}
return br.err
}
func (br *pipelineBatchResults) earlyError() error {
return br.err
}
func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, ok bool) {
if br.b != nil && br.qqIdx < len(br.b.queuedQueries) {
bi := br.b.queuedQueries[br.qqIdx]
query = bi.query
args = bi.arguments
ok = true
br.qqIdx++
}
return
}

1346
vendor/github.com/jackc/pgx/v5/conn.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More