检查 SQLite 是否具有模式并更改表格。

huangapple go评论84阅读模式
英文:

bash: check if sqlite has schema and alter table

问题

我有两个工作的代码块。

第一个检查我的sqlite3数据库是否具有特定的模式

  1. #!/bin/bash
  2. if sqlite3 my.db <<< .schema | grep -qi 'create table my_data'; then
  3. echo "all good"
  4. fi

第二个向现有数据库添加了两个新列

  1. #!/bin/bash
  2. sqlite3 my.db <<EOS
  3. ALTER TABLE my_data ADD col1 JSON DEFAULT "{}" NOT NULL;
  4. ALTER TABLE my_data ADD col2 REAL DEFAULT "0.0" NOT NULL;
  5. EOS

现在我想将它们组合成

  1. if 模式存在
  2. 添加 col1
  3. 添加 col2
  4. fi

但不幸的是,我无法让它正常运行。

英文:

I have 2 working blocks of code.

The first checks, whether my sqlite3 DB has a particular schema

  1. #!/bin/bash
  2. if sqlite3 my.db &lt;&lt;&lt; .schema | grep -qi &#39;create table my_data&#39;; then
  3. echo &quot;all good&quot;
  4. fi

The second ads two new columns to the existing DB

  1. #!/bin/bash
  2. sqlite3 my.db &lt;&lt;EOS
  3. ALTER TABLE my_data ADD col1 JSON DEFAULT &quot;{}&quot; NOT NULL;
  4. ALTER TABLE my_data ADD col2 REAL DEFAULT &quot;0.0&quot; NOT NULL;
  5. EOS

Now I would like to combine them to

  1. if schema exists
  2. add col1
  3. add col2
  4. fi

but unfortunately, I don't get it running.

答案1

得分: 0

以下是翻译好的部分:

  1. if sqlite3 my.db ".schema my_data" | grep -q 'CREATE TABLE my_data'; then
  2. sqlite3 my.db "ALTER TABLE my_data ADD col1 JSON DEFAULT '{}'' NOT NULL";
  3. sqlite3 my.db "ALTER TABLE my_data ADD col2 REAL DEFAULT 0.0 NOT NULL";
  4. fi
  5. ok, got faster to the solution myself :)
英文:
  1. if sqlite3 my.db &quot;.schema my_data&quot; | grep -q &#39;CREATE TABLE my_data&#39;; then
  2. sqlite3 my.db &quot;ALTER TABLE my_data ADD col1 JSON DEFAULT &#39;{}&#39; NOT NULL&quot;;
  3. sqlite3 my.db &quot;ALTER TABLE my_data ADD col2 REAL DEFAULT 0.0 NOT NULL&quot;;
  4. fi

ok, got faster to the solution myself 检查 SQLite 是否具有模式并更改表格。

huangapple
  • 本文由 发表于 2023年5月17日 21:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定