跳转到主要内容

使用SQLite管理您的配置

项目描述

sqlconfig:使用sqlite管理您的配置文件

问题

您的应用程序可能有很多配置存储在git中。将其作为文件存储在git仓库中有许多优点,包括

  • 差异
  • 回滚
  • 归因
  • 分支

然而,仓库中的平面文件可能会变得难以管理

  • 不同的文件需要相互同步
  • 批量操作具有挑战性
  • 很容易添加无效数据
  • 它们很杂乱

sqlconfig 为您提供存储在版本控制中的配置文件的优点,同时具有SQL的强大功能、灵活性和安全性。

解决方案

将您的配置建模为SQLite数据库。 sqlconfig 可以将数据库确定性地转换为可差异化的平面文件,这些文件位于仓库中,并再次转换为数据库。

教程

安装sqlconfig。您需要Python 3。

$ pip install sqlconfig

接下来,在SQLite中设计您的配置。在这个例子中,我们将使用Twitch的 被不公正地嘲讽的垃圾邮件系统

$ sqlconfig --shell --dir example_config --overwrite
Running shell in read-write mode.
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> create table keyword_categories (id integer primary key, name text not null unique);
sqlite> create table keywords (id integer primary key, category_id integer not null references keyword_categories(id), keyword text unique);
sqlite> insert into keyword_categories (name) values ("spam"),("hate"),("false_positives");
sqlite> insert into keywords (category_id, keyword) values (1, "viagra"),(1, "nigerian prince"),(2, "suck"),(2, "jerk"),(3, "fanny hands lane");

我们可以看到sqlconfig已经在磁盘上创建了文件

$ ls example_config/
keyword_categories.json  keywords.json  schema.sql

请注意,JSON文件被确定性地打印,并且格式易于git diff使用。

请注意,使用SQL的一个优点是编写不良配置更加困难。例如,如果我们删除一个没有删除其中所有关键字的类别,我们会得到一个错误。

$ sqlconfig --shell --dir example_config --overwrite
Running shell in read-write mode.
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> delete from keyword_categories where id=1;
sqlite>
error: 2 rows failed foreign key integrity checks. Run "pragma foreign_key_check" in the sqlite shell for more information.

读取您的配置

建议将您的 schema.sql.json 文件放入 git 仓库中,并将对这些文件的更改作为您常规代码审查或拉取请求过程的一部分。通过 CI,您可以将其发布到您选择的配置管理系统。

如果您不想直接读取文件,也可以使用 SQL 读取。可以通过命令行

$ sqlconfig --shell --dir example_config -- -header -csv 'select keyword from keywords where category_id=1'
Running shell in read-only mode. Pass --overwrite to save your changes
keyword
viagra
"nigerian prince"

或者通过使用 --load 将 SQLite 数据库导出到磁盘,然后从您的应用程序或其他工具中读取。

$ sqlconfig --load --db config.sqlite --dir example_config
$ sqlite3 config.sqlite -header -csv 'select keyword from keywords where category_id=1'
keyword
viagra
"nigerian prince"

最佳实践

最好将 schema.sql<table>.json 文件放在 git 仓库中,并使用 CI 作业将配置推送到应该提供该配置的系统。在这样做之前,使用 sqlconfig 验证配置是个好主意

$ sqlconfig --check --dir example_config/
OK

API

您可以使用 sqlconfig.lib.load(db, dir)sqlconfig.lib.dump(db, dir) 来以编程方式执行这些操作。如有任何疑问,请阅读代码 :)

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

sqlconfig-0.1.tar.gz (5.8 kB 查看哈希)

上传时间

构建分发

sqlconfig-0.1-py3-none-any.whl (6.7 kB 查看哈希)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页