Wayde's Blog

知识源于积累


  • 首页

  • 关于

  • 分类

  • 标签

  • 个人收藏

  • 归档

  • 搜索

PostgreSQL select into from和insert into from

发表于 2018-02-02 | 分类于 PostgreSQL

语句形式为:Insert into Table2(field1,field2,…) select value1,value2,… from Table1

要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量

语句形式为:SELECT vale1, value2 into Table2 from Table1

要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中

SQLAlchemy 监听事件

发表于 2018-02-01 | 分类于 Database
1
2
3
4
@event.listens_for(db.Model, 'before_update', propagate=True)
def update_lasttime(mapper, connection, target):
if hasattr(target, 'lasttime'):
target.lasttime = datetime.now()

PostgreSQL Sequence相关

发表于 2018-02-01 | 分类于 PostgreSQL
  1. 创建sequence

    CREATE SEQUENCE production_id_seq START 547 OWNED BY production.f_id;

  2. 修改sequence

    ALTER SEQUENCE production_id_seq OWNED BY production.f_id;

  3. 设置字段所使用的sequence

    1
    dbname=# alter table production alter column f_id set default nextval('production_id_seq'::regclass);
  4. 重置序列

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    dbname=# \d production_id_seq 
    Sequence "public.production_id_seq"
    Column | Type | Value
    ---------------+---------+---------------------
    sequence_name | name | production_id_seq
    last_value | bigint | 748
    start_value | bigint | 1
    increment_by | bigint | 1
    max_value | bigint | 9223372036854775807
    min_value | bigint | 1
    cache_value | bigint | 1
    log_cnt | bigint | 0
    is_cycled | boolean | f
    is_called | boolean | t
    Owned by: public.production.f_id

    dbname=# alter sequence production_id_seq restart with 302;
    dbname=# \d production_id_seq
    Sequence "public.production_id_seq"
    Column | Type | Value
    ---------------+---------+---------------------
    sequence_name | name | production_id_seq
    last_value | bigint | 302
    start_value | bigint | 1
    increment_by | bigint | 1
    max_value | bigint | 9223372036854775807
    min_value | bigint | 1
    cache_value | bigint | 1
    log_cnt | bigint | 0
    is_cycled | boolean | f
    is_called | boolean | t
    Owned by: public.production.f_id

参考资料:
在Postgres里用Sequence

Postgresql 集合处理

发表于 2018-02-01 | 分类于 PostgreSQL
  • union 并集
  • intersect 交集
  • except 差集

PostgreSQL UNION[ALL],INTERSECT [ALL],EXCEPT [ALL]

SQLAlchemy ORM

发表于 2018-02-01 | 分类于 Database
  • session.commit() vs session.flush()
  • default vs server_default

    orm默认值 vs 数据库默认值

  • onupdate vs server_onupdate

    orm自动更新 vs 数据库自动更新

  • db.engine.execute vs db.session.execute

  • engine vs session vs connection

  • db.DateTime vs db.TIMESTAMP

  • 表字段默认值default必须传方法名,不带()

    1
    2
    addtime = db.Column('f_addtime', db.TIMESTAMP, default=datetime.now)
    lasttime = db.Column('f_lasttime', db.TIMESTAMP, onupdate=datetime.now)

参考资料:
SQLAlchemy docs
SQLAlchemy: engine, connection and session difference
flask-sqlalchemy中 backref lazy的参数实例解释和选择
SQLalchemy relationship之lazy属性 学习笔记
ORM SQLAlchemy - 建立一个关系 relationship

PostgreSQL Jsonb类型操作符

发表于 2018-02-01 | 分类于 PostgreSQL
  1. ::双冒号表示类型转换
1
2
3
4
5
SELECT 1::INTEGER;
SELECT 1::VARCHAR;
SELECT '1'::INTEGER;
SELECT '1'::VARCHAR;
SELECT 'a'::INTEGER;
Operator Right Operand Type Description Example
@> jsonb Does the left JSON value contain within it the right value? '{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb
<@ jsonb Is the left JSON value contained within the right value? '{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb
? text Does the key/element string exist within the JSON value? '{"a":1, "b":2}'::jsonb ? 'b'
`? ` text[] Do any of these key/element strings exist? `’{“a”:1, “b”:2, “c”:3}’::jsonb ? array[‘b’, ‘c’]`
?& text[] Do all of these key/element strings exist? '["a", "b"]'::jsonb ?& array['a', 'b']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' @> '["人物","道具"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' @> '["道具","人物"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' @> '["人物"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' @> '["道具"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' @> '["道具", "不存在"]';

SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' <@ '["人物","道具"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' <@ '["道具","人物"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' <@ '["人物"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' <@ '["道具"]';
SELECT '{"模型分类": ["人物", "道具"], "模型面数": ["低模"]}'::jsonb->'模型分类' <@ '["道具", "不存在"]';

SELECT '{"模型分类": ["人物","道具"],"模型面数": ["低模"]}'::JSONB->'模型分类' ?| ARRAY['道具','不存在'];
SELECT '{"模型分类": ["人物","道具"],"模型面数": ["低模"]}'::JSONB->'模型分类' ?& ARRAY['道具','不存在'];

SELECT ARRAY['a', 'b'] @> ARRAY['a'];
SELECT ARRAY['a', 'b'] @> ARRAY['b'];
SELECT ARRAY['a', 'b'] @> ARRAY['b','c'];

SELECT ARRAY['a', 'b'] <@ ARRAY['a'];
SELECT ARRAY['a', 'b'] <@ ARRAY['b'];
SELECT ARRAY['a', 'b'] <@ ARRAY['b','c'];

SELECT ARRAY['a', 'b'] && ARRAY['a'];
SELECT ARRAY['a', 'b'] && ARRAY['b'];
SELECT ARRAY['a', 'b'] && ARRAY['b','c'];

参考资料:
9.15. JSON Functions and Operators
JSON Functions and Operators
8.14. JSON Types
Querying JSON in Postgres
PostgreSQL 9.4.4 中文手册
PostgreSQL 9.4.4 中文手册 章 8. 数据类型
Array Functions and Operators

Git 常用命令

发表于 2017-12-16 | 分类于 Git

本地新建项目并关联到远程仓库

git init
git remote add origin repository-url
git push --set-upstream origin master

添加远程仓库地址

git remote set-url origin new-repository-url

恢复单个文件版本

git checkout <hash> <filename>

导出代码

git archive -o ../updated.zip HEAD $(git diff --name-only HEAD^)

移除版本控制

1
2
git rm -r -n --cached docs/api	# -n 预览命令,并不真正删除
git rm -r --cached docs/api

将某个commit移动到其它branch

git cherry-pick <commit id>

阅读全文 »

Python 排序方法list.sort()和sorted()

发表于 2017-12-16 | 分类于 Python

list.sort()

List的成员函数,所以仅适用list排序,原址排序

1
2
3
4
5
6
7
8
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
# cmp -- 比较函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
# 返回值:None
# 注: Python3开始取消cmp参数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
list_a = [26, 2, 10, 20, 11, 8]
list_a.sort()
print(list_a)
#[2, 8, 10, 11, 20, 26]

list_b = ['Way-26','Way-2','Way-10','Way-20','Way-11','Way-8']
list_b.sort(key=lambda x : int(x[4:]))
print(list_b)
#['Way-2', 'Way-8', 'Way-10', 'Way-11', 'Way-20', 'Way-26']

list_c = ['Way-26','Way-2','Way-10','Way-20','Way-11','Way-8']
list_c.sort(cmp=lambda x,y : int(x[4:])-int(y[4:]))
print(list_c)
#['Way-2', 'Way-8', 'Way-10', 'Way-11', 'Way-20', 'Way-26']

list_d = ['Way-26','Way-2','Way-10','Way-20','Way-11','Way-8']
list_d.sort(cmp=lambda x,y : y-x, key=lambda x : int(x[4:]))
print(list_d)
#['Way-26', 'Way-20', 'Way-11', 'Way-10', 'Way-8', 'Way-2']

sorted()

内建函数,适用于任何可迭代对象,返回排序后的对象

1
2
3
4
5
6
7
8
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
# iterable -- 可迭代对象。
# cmp -- 比较函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代 对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
# 返回值:排序后的对象
# 注: Python3开始取消cmp参数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
iter_a = [dict(num=26),dict(num=2),dict(num=10),dict(num=20),dict(num=11),dict(num=8)]
result = sorted(iter_a, key=lambda x: x['num'], reverse=True)
print(result)
#[{'num': 26}, {'num': 20}, {'num': 11}, {'num': 10}, {'num': 8}, {'num': 2}]

# 利用operator.itemgetter模块排序元组
from operator import itemgetter
iter_b = [
('Wayde', 28, 90),
('Peter', 23, 80),
('Bob', 32, 100),
]
result = sorted(iter_b, key=itemgetter(2))
print(result)
#[('Peter', 23, 80), ('Wayde', 28, 90), ('Bob', 32, 100)]

# 利用operator.attrgetter模块排序元组
from operator import attrgetter
class Student(object):
def __init__(self, *args, **kwargs):
self.name = kwargs['name']
self.age = kwargs['age']
self.score = kwargs['score']

def __repr__(self):
return repr(self.name)

iter_c = [
Student(name='Wayde', age=28, score=90),
Student(name='Peter', age=23, score=80),
Student(name='Bob', age=32, score=100),
Student(name='Jack', age=28, score=95),
Student(name='Aaron', age=35, score=90),
]

result = sorted(iter_c, key=attrgetter('age'))
print(result)
#['Peter', 'Aaron', 'Wayde', 'Jack', 'Bob']

# 多级排序
result = sorted(iter_c, key=attrgetter('score','age'))
print(result)
#['Peter', 'Wayde', 'Aaron', 'Jack', 'Bob']

参考资料:
Python中sorted函数的用法

Git ignore某个目录除某某文件

发表于 2017-12-16 | 分类于 Git
1
2
3
4
# For doc
/docs/*
!/docs/apidoc.json
!/docs/generate.sh

Git submodule说明

发表于 2017-12-16 | 分类于 Git

以下示例: 父项目为box-server,子项目为box-deploy

添加submodule

  1. cd box-server
  2. git submodule add box-deploy-repository-url deploy
  3. git ci -m 'add submodule deploy'

clone含有submodule的项目

  1. 方法一(推荐)
    • git clone --recursive box-server-repository-url
  2. 方法二
    • git clone box-server-repository-url
    • git submodule init
    • git submodule update
  3. 方法三
    • git clone box-server-repository-url
    • git submodule update --init --recursive
阅读全文 »
1…8910…14
Wayde

Wayde

140 日志
14 分类
112 标签
GitHub StackOverflow Instagram
© 2012–2022 Wayde
粤ICP备2020135844号