Sqly - An easy-to-use extension for sqlx, base on xml files and named query/exec

sqly


An easy-to-use extension for sqlx ,base on xml files and named query/exec

this repo is under development, please do not use it in production.

install

go get github.com/nvac/sqly

Usage

1. set database config in xml file

  • name: needs to be unique in same environment
  • environment: custom string,runtime environment
  • source: data source name
  • connMaxLifetime(seconds): sets the maximum amount of time a connection may be reused. . if default values is required, remove the attr
  • connMaxIdleTime(seconds): sets the maximum amount of time a connection may be idle. if default values is required, remove the attr
  • maxIdleConns: sets the maximum number of connections in the idle connection pool. if default values is required, remove the attr
  • maxOpenConns: sets the maximum number of open connections to the database. if default values is required, remove the attr
<?xml version="1.0" encoding="utf-8" ?>

<databases>
    <database name="ReadDb"
              environment="development"
              driver="mysql"
              source="user:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&amp;parseTime=True"
              connMaxLifetime="30"
              connMaxIdleTime="30"
              maxIdleConns="2"
              maxOpenConns="10"
    />
    
    <database name="WriteDb"
              environment="development"
              driver="mysql"
              source="user:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&amp;parseTime=True"
              connMaxLifetime="30"
              connMaxIdleTime="30"
              maxIdleConns="2"
              maxOpenConns="10"
    />
</databases>

2. write sql script in xml file

  • name: needs to be unique
  • database: using the above configured database
  • content: ensure in CDATA
<?xml version="1.0" encoding="utf-8" ?>

<scripts>
    <script name="GetUser" database="ReadDb">
        <![CDATA[
            SELECT username, password
            FROM `user`
            WHERE username = :username
        ]]>
    </script>

    <script name="ListUser" database="ReadDb">
        <![CDATA[
            SELECT username, password
            FROM `user`
            LIMIT 10 OFFSET 0
        ]]>
    </script>
    
    <script name="AddUser" database="WriteDb">
        <![CDATA[
            INSERT INTO user (username, password)
            VALUES (:username, :password)
        ]]>
    </script>
</scripts>
  1. inti & use sqly
package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"os"
)

type User struct {
	Username string `db:"username"`
	Password string `db:"password"`
}

func main() {
	err := sqly.Init(&Config{
		DatabasesFile:    "config/databases.xml",
		ScriptsGlobFiles: "config/scripts/*.xml",
		Environment:      os.Getenv("Environment"),
		SourceDecryptFunc: func(source string) string {
			return source
		},
	})

	if err != nil {
		panic(err)
	}

	var user User
	if err := sqly.QueryRow("GetUser", &user, map[string]interface{}{
		"username": "lisa",
	}); err != nil {
		panic(err)
	} else {
		fmt.Println(user)
	}

	var users []User
	if err := sqly.QueryRows("ListUser", &users, map[string]interface{}{}); err != nil {
		panic(err)
	} else {
		fmt.Println(users)
	}

	if result, err := sqly.Exec("AddUser", map[string]interface{}{
	    "username": "root",
		"password": "123456",
	}); err != nil {
		panic(err)
    } else {
		fmt.Println(result.RowsAffected())
		fmt.Println(result.LastInsertId())
    }
}

License

MIT © nvac

Similar Resources

axmlfmt is an opinionated formatter for Android XML resources

axmlfmt axmlfmt is an opinionated formatter for Android XML resources. It takes XML that looks like ?xml version="1.0" encoding="utf-8"? LinearLayo

May 14, 2022

Freestyle xml parser with golang

fxml - FreeStyle XML Parser This package provides a simple parser which reads a XML document and output a tree structure, which does not need a pre-de

Jul 1, 2022

🧑‍💻 Go XML generator without Structs™

exml 🧑‍💻 Go XML generator without Structs™ Package exml allows XML documents to be generated without the usage of structs or maps. It is not intende

Nov 15, 2022

wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format.

wikipedia-jsonl wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format. How to use At first, download the XML dump from Wikime

Dec 26, 2022

A fast, easy-of-use and dependency free custom mapping from .csv data into Golang structs

csvparser This package provides a fast and easy-of-use custom mapping from .csv data into Golang structs. Index Pre-requisites Installation Examples C

Nov 14, 2022

An extension to the Goldmark Markdown Parser

Goldmark-Highlight An extension to the Goldmark Markdown Parser which adds parsing / rendering capabilities for rendering highlighted text. Highlighte

May 25, 2022

htmlquery is golang XPath package for HTML query.

htmlquery Overview htmlquery is an XPath query package for HTML, lets you extract data or evaluate from HTML documents by an XPath expression. htmlque

Jan 4, 2023

Parse data and test fixtures from markdown files, and patch them programmatically, too.

go-testmark Do you need test fixtures and example data for your project, in a language agnostic way? Do you want it to be easy to combine with documen

Oct 31, 2022

Easy AWK-style text processing in Go

awk Description awk is a package for the Go programming language that provides an AWK-style text processing capability. The package facilitates splitt

Jul 25, 2022
Related tags
:book: A Golang library for text processing, including tokenization, part-of-speech tagging, and named-entity extraction.

prose prose is a natural language processing library (English only, at the moment) in pure Go. It supports tokenization, segmentation, part-of-speech

Jan 4, 2023
Quick and simple parser for PFSense XML configuration files, good for auditing firewall rules

pfcfg-parser version 0.0.1 : 13 January 2022 A quick and simple parser for PFSense XML configuration files to generate a plain text file of the main c

Jan 13, 2022
Decode / encode XML to/from map[string]interface{} (or JSON); extract values with dot-notation paths and wildcards. Replaces x2j and j2x packages.

mxj - to/from maps, XML and JSON Decode/encode XML to/from map[string]interface{} (or JSON) values, and extract/modify values from maps by key or key-

Dec 29, 2022
omniparser: a native Golang ETL streaming parser and transform library for CSV, JSON, XML, EDI, text, etc.
omniparser: a native Golang ETL streaming parser and transform library for CSV, JSON, XML, EDI, text, etc.

omniparser Omniparser is a native Golang ETL parser that ingests input data of various formats (CSV, txt, fixed length/width, XML, EDI/X12/EDIFACT, JS

Jan 4, 2023
Convert xml and json to go struct

xj2go The goal is to convert xml or json file to go struct file. Usage Download and install it: $ go get -u -v github.com/wk30/xj2go/cmd/... $ xj [-t

Oct 23, 2022
parse and generate XML easily in go

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 Ele

Dec 19, 2022
'go test' runner with output optimized for humans, JUnit XML for CI integration, and a summary of the test results.
'go test' runner with output optimized for humans, JUnit XML for CI integration, and a summary of the test results.

gotestsum gotestsum runs tests using go test --json, prints formatted test output, and a summary of the test run. It is designed to work well for both

Dec 28, 2022
Go XML sitemap and sitemap index generator

Install go get github.com/turk/go-sitemap Example for sitemapindex func () main(c *gin.Context) { s := sitemap.NewSitemapIndex(c.Writer, true)

Jun 29, 2022
This package provides Go (golang) types and helper functions to do some basic but useful things with mxGraph diagrams in XML, which is most famously used by app.diagrams.net, the new name of draw.io.

Go Draw - Golang MX This package provides types and helper functions to do some basic but useful things with mxGraph diagrams in XML, which is most fa

Aug 30, 2022
Extraction politique de conformité : xlsx (fichier de suivi) -> xml (format AlgoSec)

go_policyExtractor Extraction politique de conformité : xlsx (fichier de suivi) -> xml (format AlgoSec). Le programme suivant se base sur les intitulé

Nov 4, 2021