perf: sorted set value support format viewing #65

This commit is contained in:
Lykin 2023-11-15 23:41:53 +08:00
parent 2a3a15d64d
commit fea87662de
13 changed files with 382 additions and 264 deletions

View File

@ -681,12 +681,11 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
case "hash": case "hash":
loadHashHandle := func() ([]types.HashEntryItem, bool, error) { loadHashHandle := func() ([]types.HashEntryItem, bool, error) {
//items := map[string]string{} var items []types.HashEntryItem
scanSize := int64(Preferences().GetScanSize())
items := make([]types.HashEntryItem, 0, scanSize)
var loadedVal []string var loadedVal []string
var cursor uint64 var cursor uint64
var subErr error var subErr error
scanSize := int64(Preferences().GetScanSize())
if param.Full { if param.Full {
// load all // load all
cursor = 0 cursor = 0
@ -702,7 +701,7 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
}) })
if doConvert { if doConvert {
if dv, _, _ := strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format); dv != loadedVal[i+1] { if dv, _, _ := strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format); dv != loadedVal[i+1] {
items[i/2].DisplayValue = dv items[len(items)-1].DisplayValue = dv
} }
} }
} }
@ -716,11 +715,11 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
if subErr != nil { if subErr != nil {
return nil, false, subErr return nil, false, subErr
} }
for i := 0; i < len(loadedVal); i += 2 { loadedLen := len(loadedVal)
items = append(items, types.HashEntryItem{ items = make([]types.HashEntryItem, loadedLen/2)
Key: loadedVal[i], for i := 0; i < loadedLen; i += 2 {
Value: strutil.EncodeRedisKey(loadedVal[i+1]), items[i/2].Key = loadedVal[i]
}) items[i/2].Value = strutil.EncodeRedisKey(loadedVal[i+1])
if doConvert { if doConvert {
if dv, _, _ := strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format); dv != loadedVal[i+1] { if dv, _, _ := strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format); dv != loadedVal[i+1] {
items[i/2].DisplayValue = dv items[i/2].DisplayValue = dv
@ -744,8 +743,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
var items []types.SetEntryItem var items []types.SetEntryItem
var cursor uint64 var cursor uint64
var subErr error var subErr error
scanSize := int64(Preferences().GetScanSize())
var loadedKey []string var loadedKey []string
scanSize := int64(Preferences().GetScanSize())
if param.Full { if param.Full {
// load all // load all
cursor = 0 cursor = 0
@ -754,6 +753,16 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
if subErr != nil { if subErr != nil {
return items, false, subErr return items, false, subErr
} }
for _, val := range loadedKey {
items = append(items, types.SetEntryItem{
Value: val,
})
if doConvert {
if dv, _, _ := strutil.ConvertTo(val, param.Decode, param.Format); dv != val {
items[len(items)-1].DisplayValue = dv
}
}
}
if cursor == 0 { if cursor == 0 {
break break
} }
@ -761,9 +770,6 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} else { } else {
cursor, _ = getEntryCursor() cursor, _ = getEntryCursor()
loadedKey, cursor, subErr = client.SScan(ctx, key, cursor, param.MatchPattern, scanSize).Result() loadedKey, cursor, subErr = client.SScan(ctx, key, cursor, param.MatchPattern, scanSize).Result()
}
setEntryCursor(cursor)
items = make([]types.SetEntryItem, len(loadedKey)) items = make([]types.SetEntryItem, len(loadedKey))
for i, val := range loadedKey { for i, val := range loadedKey {
items[i].Value = val items[i].Value = val
@ -773,6 +779,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} }
} }
} }
}
setEntryCursor(cursor)
return items, cursor == 0, nil return items, cursor == 0, nil
} }
@ -784,8 +792,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} }
case "zset": case "zset":
loadZSetHandle := func() ([]types.ZSetItem, bool, error) { loadZSetHandle := func() ([]types.ZSetEntryItem, bool, error) {
var items []types.ZSetItem var items []types.ZSetEntryItem
var cursor uint64 var cursor uint64
scanSize := int64(Preferences().GetScanSize()) scanSize := int64(Preferences().GetScanSize())
var loadedVal []string var loadedVal []string
@ -800,10 +808,15 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
var score float64 var score float64
for i := 0; i < len(loadedVal); i += 2 { for i := 0; i < len(loadedVal); i += 2 {
if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil { if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil {
items = append(items, types.ZSetItem{ items = append(items, types.ZSetEntryItem{
Value: loadedVal[i], Value: loadedVal[i],
Score: score, Score: score,
}) })
if doConvert {
if dv, _, _ := strutil.ConvertTo(loadedVal[i], param.Decode, param.Format); dv != loadedVal[i] {
items[len(items)-1].DisplayValue = dv
}
}
} }
} }
if cursor == 0 { if cursor == 0 {
@ -813,13 +826,18 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} else { } else {
cursor, _ = getEntryCursor() cursor, _ = getEntryCursor()
loadedVal, cursor, err = client.ZScan(ctx, key, cursor, param.MatchPattern, scanSize).Result() loadedVal, cursor, err = client.ZScan(ctx, key, cursor, param.MatchPattern, scanSize).Result()
loadedLen := len(loadedVal)
items = make([]types.ZSetEntryItem, loadedLen/2)
var score float64 var score float64
for i := 0; i < len(loadedVal); i += 2 { for i := 0; i < loadedLen; i += 2 {
if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil { if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil {
items = append(items, types.ZSetItem{ items[i/2].Score = score
Value: loadedVal[i], items[i/2].Value = loadedVal[i]
Score: score, if doConvert {
}) if dv, _, _ := strutil.ConvertTo(loadedVal[i], param.Decode, param.Format); dv != loadedVal[i] {
items[i/2].DisplayValue = dv
}
}
} }
} }
} }
@ -835,9 +853,9 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} }
case "stream": case "stream":
loadStreamHandle := func() ([]types.StreamItem, bool, error) { loadStreamHandle := func() ([]types.StreamEntryItem, bool, error) {
var msgs []redis.XMessage var msgs []redis.XMessage
var items []types.StreamItem var items []types.StreamEntryItem
var last string var last string
if param.Full { if param.Full {
// load all // load all
@ -865,7 +883,7 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} }
setEntryXLast(last) setEntryXLast(last)
for _, msg := range msgs { for _, msg := range msgs {
items = append(items, types.StreamItem{ items = append(items, types.StreamEntryItem{
ID: msg.ID, ID: msg.ID,
Value: msg.Values, Value: msg.Values,
}) })
@ -1227,8 +1245,8 @@ func (b *browserService) SetListItem(param types.SetListParam) (resp types.JSRes
} }
// SetSetItem add members to set or remove from set // SetSetItem add members to set or remove from set
func (b *browserService) SetSetItem(connName string, db int, k any, remove bool, members []any) (resp types.JSResp) { func (b *browserService) SetSetItem(server string, db int, k any, remove bool, members []any) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(server, db)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
@ -1289,45 +1307,54 @@ func (b *browserService) UpdateSetItem(param types.SetSetParam) (resp types.JSRe
} }
// UpdateZSetValue update value of sorted set member // UpdateZSetValue update value of sorted set member
func (b *browserService) UpdateZSetValue(connName string, db int, k any, value, newValue string, score float64) (resp types.JSResp) { func (b *browserService) UpdateZSetValue(param types.SetZSetParam) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(param.Server, param.DB)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
client, ctx := item.client, item.ctx client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k) key := strutil.DecodeRedisKey(param.Key)
updated := map[string]any{} val, newVal := strutil.DecodeRedisKey(param.Value), strutil.DecodeRedisKey(param.NewValue)
updated := map[string]float64{}
var removed []string var removed []string
if len(newValue) <= 0 { if len(newVal) <= 0 {
// blank new value, delete value // no new value, delete value
_, err = client.ZRem(ctx, key, value).Result() _, err = client.ZRem(ctx, key, val).Result()
if err == nil { if err == nil {
removed = append(removed, value) removed = append(removed, val)
} }
} else if newValue == value { } else {
var saveVal string
if saveVal, err = strutil.SaveAs(newVal, param.Format, param.Decode); err != nil {
resp.Msg = fmt.Sprintf(`save to type "%s" fail: %s`, param.Format, err.Error())
return
}
if saveVal == val {
// update score only // update score only
_, err = client.ZAdd(ctx, key, redis.Z{ _, err = client.ZAdd(ctx, key, redis.Z{
Score: score, Score: param.Score,
Member: value, Member: saveVal,
}).Result() }).Result()
if err == nil { if err == nil {
updated[value] = score updated[saveVal] = param.Score
} }
} else { } else {
// remove old value and add new one // remove old value and add new one
_, err = client.ZRem(ctx, key, value).Result() _, err = client.ZRem(ctx, key, val).Result()
if err == nil { if err == nil {
removed = append(removed, value) removed = append(removed, val)
} }
_, err = client.ZAdd(ctx, key, redis.Z{ _, err = client.ZAdd(ctx, key, redis.Z{
Score: score, Score: param.Score,
Member: newValue, Member: saveVal,
}).Result() }).Result()
if err == nil { if err == nil {
updated[newValue] = score updated[saveVal] = param.Score
}
} }
} }
if err != nil { if err != nil {

View File

@ -79,3 +79,14 @@ type SetSetParam struct {
Format string `json:"format,omitempty"` Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"` Decode string `json:"decode,omitempty"`
} }
type SetZSetParam struct {
Server string `json:"server"`
DB int `json:"db"`
Key any `json:"key"`
Value any `json:"value"`
NewValue any `json:"newValue"`
Score float64 `json:"score"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
}

View File

@ -16,12 +16,13 @@ type SetEntryItem struct {
DisplayValue string `json:"dv,omitempty"` DisplayValue string `json:"dv,omitempty"`
} }
type ZSetItem struct { type ZSetEntryItem struct {
Value string `json:"value"` Score float64 `json:"s"`
Score float64 `json:"score"` Value string `json:"v"`
DisplayValue string `json:"dv,omitempty"`
} }
type StreamItem struct { type StreamEntryItem struct {
ID string `json:"id"` ID string `json:"id"`
Value map[string]any `json:"value"` Value map[string]any `json:"value"`
} }

View File

@ -206,11 +206,11 @@ func autoViewAs(str string) (value, resultFormat string) {
} }
func decodeJson(str string) (string, bool) { func decodeJson(str string) (string, bool) {
str = strings.TrimSpace(str) trimedStr := strings.TrimSpace(str)
if (strings.HasPrefix(str, "{") && strings.HasSuffix(str, "}")) || if (strings.HasPrefix(trimedStr, "{") && strings.HasSuffix(trimedStr, "}")) ||
(strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]")) { (strings.HasPrefix(trimedStr, "[") && strings.HasSuffix(trimedStr, "]")) {
var out bytes.Buffer var out bytes.Buffer
if err := json.Indent(&out, []byte(str), "", " "); err == nil { if err := json.Indent(&out, []byte(trimedStr), "", " "); err == nil {
return out.String(), true return out.String(), true
} }
} }
@ -282,9 +282,9 @@ func decodeBrotli(str string) (string, bool) {
return str, false return str, false
} }
func SaveAs(str, viewType, decodeType string) (value string, err error) { func SaveAs(str, format, decode string) (value string, err error) {
value = str value = str
switch viewType { switch format {
case types.FORMAT_JSON: case types.FORMAT_JSON:
if jsonStr, ok := encodeJson(str); ok { if jsonStr, ok := encodeJson(str); ok {
value = jsonStr value = jsonStr
@ -310,7 +310,7 @@ func SaveAs(str, viewType, decodeType string) (value string, err error) {
} }
} }
switch decodeType { switch decode {
case types.DECODE_NONE: case types.DECODE_NONE:
return return
@ -350,19 +350,16 @@ func SaveAs(str, viewType, decodeType string) (value string, err error) {
} }
return return
} }
return str, errors.New("fail to save with unknown error") return str, nil
} }
func encodeJson(str string) (string, bool) { func encodeJson(str string) (string, bool) {
var data any var dst bytes.Buffer
if err := json.Unmarshal([]byte(str), &data); err == nil { if err := json.Compact(&dst, []byte(str)); err != nil {
var jsonByte []byte
if jsonByte, err = json.Marshal(data); err == nil {
return string(jsonByte), true
}
}
return str, false return str, false
} }
return dst.String(), true
}
func encodeBase64(str string) (string, bool) { func encodeBase64(str string) (string, bool) {
return base64.StdEncoding.EncodeToString([]byte(str)), true return base64.StdEncoding.EncodeToString([]byte(str)), true

View File

@ -95,8 +95,8 @@ const pinBtnStyle = computed(() => ({
/** /**
* *
* @param {string} decode * @param {decodeTypes} decode
* @param {string} format * @param {formatTypes} format
* @return {Promise<void>} * @return {Promise<void>}
*/ */
const onFormatChanged = async (decode = '', format = '') => { const onFormatChanged = async (decode = '', format = '') => {
@ -164,6 +164,7 @@ const onSave = () => {
autofocus autofocus
class="flex-item-expand" class="flex-item-expand"
type="textarea" type="textarea"
:resizable="false"
@update:value="onUpdateValue" /> @update:value="onUpdateValue" />
<format-selector <format-selector
:decode="viewAs.decode" :decode="viewAs.decode"

View File

@ -132,9 +132,9 @@ const valueColumn = reactive({
}) })
const startEdit = async (no, key, value) => { const startEdit = async (no, key, value) => {
currentEditRow.value = value
currentEditRow.no = no currentEditRow.no = no
currentEditRow.key = key currentEditRow.key = key
currentEditRow.value = value
} }
const saveEdit = async (field, value, decode, format) => { const saveEdit = async (field, value, decode, format) => {
@ -194,13 +194,14 @@ const actionColumn = {
onEdit: () => startEdit(index + 1, row.k, row.v), onEdit: () => startEdit(index + 1, row.k, row.v),
onDelete: async () => { onDelete: async () => {
try { try {
const { success, msg } = await browserStore.removeHashField( const { removed, success, msg } = await browserStore.removeHashField(
props.name, props.name,
props.db, props.db,
keyName.value, keyName.value,
row.k, row.k,
) )
if (success) { if (success) {
props.value.splice(index, 1)
$message.success(i18n.t('dialogue.delete_key_succ', { key: row.k })) $message.success(i18n.t('dialogue.delete_key_succ', { key: row.k }))
} else { } else {
$message.error(msg) $message.error(msg)

View File

@ -33,7 +33,11 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: Object, value: {
// [{v: string|number[], dv: string}]
type: Array,
default: () => {},
},
size: Number, size: Number,
length: Number, length: Number,
format: { format: {
@ -97,16 +101,16 @@ const valueColumn = reactive({
}) })
const startEdit = async (no, value) => { const startEdit = async (no, value) => {
currentEditRow.value = value
currentEditRow.no = no currentEditRow.no = no
currentEditRow.value = value
} }
/** /**
* *
* @param {string|number} pos * @param {string|number} pos
* @param {string} value * @param {string} value
* @param {string} decode * @param {decodeTypes} decode
* @param {string} format * @param {formatTypes} format
* @return {Promise<void>} * @return {Promise<void>}
*/ */
const saveEdit = async (pos, value, decode, format) => { const saveEdit = async (pos, value, decode, format) => {
@ -171,6 +175,7 @@ const actionColumn = {
index, index,
) )
if (success) { if (success) {
props.value.splice(index, 1)
$message.success(i18n.t('dialogue.delete_key_succ', { key: `#${index + 1}` })) $message.success(i18n.t('dialogue.delete_key_succ', { key: `#${index + 1}` }))
} else { } else {
$message.error(msg) $message.error(msg)

View File

@ -33,7 +33,10 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: Array, value: {
type: Array,
default: () => [],
},
size: Number, size: Number,
length: Number, length: Number,
format: { format: {
@ -97,16 +100,16 @@ const valueColumn = reactive({
}) })
const startEdit = async (no, value) => { const startEdit = async (no, value) => {
currentEditRow.value = value
currentEditRow.no = no currentEditRow.no = no
currentEditRow.value = value
} }
/** /**
* *
* @param {string|number} pos * @param {string|number} pos
* @param {string} value * @param {string} value
* @param {string} decode * @param {decodeTypes} decode
* @param {string} format * @param {formatTypes} format
* @return {Promise<void>} * @return {Promise<void>}
*/ */
const saveEdit = async (pos, value, decode, format) => { const saveEdit = async (pos, value, decode, format) => {
@ -171,6 +174,7 @@ const actionColumn = {
row.v, row.v,
) )
if (success) { if (success) {
props.value.splice(index, 1)
$message.success(i18n.t('dialogue.delete_key_succ', { key: row.v })) $message.success(i18n.t('dialogue.delete_key_succ', { key: row.v }))
} else { } else {
$message.error(msg) $message.error(msg)

View File

@ -66,14 +66,15 @@ const keyName = computed(() => {
const loadData = async (reset, full) => { const loadData = async (reset, full) => {
try { try {
const { name, db, view, decodeType, matchPattern, decode, format } = data.value if (!!props.blank) {
return
}
const { name, db, matchPattern, decode, format } = data.value
reset = reset === true reset = reset === true
await browserStore.loadKeyDetail({ await browserStore.loadKeyDetail({
server: name, server: name,
db: db, db: db,
key: keyName.value, key: keyName.value,
viewType: view,
decodeType: decodeType,
matchPattern: matchPattern, matchPattern: matchPattern,
decode: reset ? decodeTypes.NONE : decode, decode: reset ? decodeTypes.NONE : decode,
format: reset ? formatTypes.RAW : format, format: reset ? formatTypes.RAW : format,

View File

@ -3,10 +3,10 @@ import { computed, h, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.vue' import ContentToolbar from './ContentToolbar.vue'
import AddLink from '@/components/icons/AddLink.vue' import AddLink from '@/components/icons/AddLink.vue'
import { NButton, NCode, NIcon, NInput, NInputNumber, useThemeVars } from 'naive-ui' import { NButton, NIcon, NInput, useThemeVars } from 'naive-ui'
import { types, types as redisTypes } from '@/consts/support_redis_type.js' import { types, types as redisTypes } from '@/consts/support_redis_type.js'
import EditableTableColumn from '@/components/common/EditableTableColumn.vue' import EditableTableColumn from '@/components/common/EditableTableColumn.vue'
import { isEmpty, size } from 'lodash' import { head, isEmpty, keys, size } from 'lodash'
import useDialogStore from 'stores/dialog.js' import useDialogStore from 'stores/dialog.js'
import bytes from 'bytes' import bytes from 'bytes'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js' import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
@ -14,6 +14,9 @@ import useBrowserStore from 'stores/browser.js'
import LoadList from '@/components/icons/LoadList.vue' import LoadList from '@/components/icons/LoadList.vue'
import LoadAll from '@/components/icons/LoadAll.vue' import LoadAll from '@/components/icons/LoadAll.vue'
import IconButton from '@/components/common/IconButton.vue' import IconButton from '@/components/common/IconButton.vue'
import ContentEntryEditor from '@/components/content_value/ContentEntryEditor.vue'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
import Edit from '@/components/icons/Edit.vue'
const i18n = useI18n() const i18n = useI18n()
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -30,12 +33,15 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: Object, value: {
type: Array,
default: () => [],
},
size: Number, size: Number,
length: Number, length: Number,
viewAs: { format: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.RAW,
}, },
decode: { decode: {
type: String, type: String,
@ -70,11 +76,22 @@ const filterType = ref(1)
const browserStore = useBrowserStore() const browserStore = useBrowserStore()
const dialogStore = useDialogStore() const dialogStore = useDialogStore()
const keyType = redisTypes.ZSET const keyType = redisTypes.ZSET
const currentEditRow = ref({ const currentEditRow = reactive({
no: 0, no: 0,
score: 0, score: 0,
value: null, value: null,
format: formatTypes.RAW,
decode: decodeTypes.NONE,
}) })
const inEdit = computed(() => {
return currentEditRow.no > 0
})
const fullEdit = ref(false)
const inFullEdit = computed(() => {
return inEdit.value && fullEdit.value
})
const scoreColumn = reactive({ const scoreColumn = reactive({
key: 'score', key: 'score',
title: i18n.t('interface.score'), title: i18n.t('interface.score'),
@ -83,7 +100,7 @@ const scoreColumn = reactive({
resizable: true, resizable: true,
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
const score = parseFloat(row.score) const score = parseFloat(row.s)
if (isNaN(score)) { if (isNaN(score)) {
return true return true
} }
@ -110,23 +127,12 @@ const scoreColumn = reactive({
} }
} }
} else { } else {
return !!~row.value.indexOf(value.toString()) return !!~row.v.indexOf(value.toString())
} }
return true return true
}, },
render: (row) => { render: (row) => {
const isEdit = currentEditRow.value.no === row.no return row.s
if (isEdit) {
return h(NInputNumber, {
value: currentEditRow.value.score,
'onUpdate:value': (val) => {
currentEditRow.value.score = val
},
})
} else {
return row.score
}
}, },
}) })
const valueColumn = reactive({ const valueColumn = reactive({
@ -139,33 +145,64 @@ const valueColumn = reactive({
tooltip: true, tooltip: true,
}, },
filterOptionValue: null, filterOptionValue: null,
className: inEdit ? 'clickable' : '',
filter(value, row) { filter(value, row) {
return !!~row.value.indexOf(value.toString()) return !!~row.v.indexOf(value.toString())
}, },
// sorter: (row1, row2) => row1.value - row2.value, // sorter: (row1, row2) => row1.value - row2.value,
// ellipsis: {
// tooltip: true
// },
render: (row) => { render: (row) => {
const isEdit = currentEditRow.value.no === row.no return row.dv || row.v
if (isEdit) {
return h(NInput, {
value: currentEditRow.value.value,
type: 'textarea',
autosize: { minRow: 2, maxRows: 5 },
style: 'text-align: left;',
'onUpdate:value': (val) => {
currentEditRow.value.value = val
},
})
} else {
return h(NCode, { language: 'plaintext', wordWrap: true }, { default: () => row.value })
}
}, },
}) })
const cancelEdit = () => { const startEdit = async (no, score, value) => {
currentEditRow.value.no = 0 currentEditRow.no = no
currentEditRow.score = score
currentEditRow.value = value
}
const saveEdit = async (field, value, decode, format) => {
try {
const score = parseFloat(field)
const row = props.value[currentEditRow.no - 1]
if (row == null) {
throw new Error('row not exists')
}
const { updated, success, msg } = await browserStore.updateZSetItem({
server: props.name,
db: props.db,
key: keyName.value,
value: row.v,
newValue: value,
score,
decode,
format,
})
if (success) {
row.v = head(keys(updated))
row.s = updated[row.v]
const { value: displayVal } = await browserStore.convertValue({
value: row.v,
decode: props.decode,
format: props.format,
})
row.dv = displayVal
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
}
}
const resetEdit = () => {
currentEditRow.no = 0
currentEditRow.score = 0
currentEditRow.value = null
currentEditRow.format = formatTypes.RAW
currentEditRow.decode = decodeTypes.NONE
} }
const actionColumn = { const actionColumn = {
@ -175,25 +212,22 @@ const actionColumn = {
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
fixed: 'right', fixed: 'right',
render: (row) => { render: (row, index) => {
return h(EditableTableColumn, { return h(EditableTableColumn, {
editing: currentEditRow.value.no === row.no, editing: false,
bindKey: row.value, bindKey: row.v,
onEdit: () => { onEdit: () => startEdit(index + 1, row.s, row.v),
currentEditRow.value.no = row.no
currentEditRow.value.value = row.value
currentEditRow.value.score = row.score
},
onDelete: async () => { onDelete: async () => {
try { try {
const { success, msg } = await browserStore.removeZSetItem( const { success, msg } = await browserStore.removeZSetItem(
props.name, props.name,
props.db, props.db,
keyName.value, keyName.value,
row.value, row.v,
) )
if (success) { if (success) {
$message.success(i18n.t('dialogue.delete_key_succ', { key: row.value })) props.value.splice(index, 1)
$message.success(i18n.t('dialogue.delete_key_succ', { key: row.v }))
} else { } else {
$message.error(msg) $message.error(msg)
} }
@ -201,66 +235,51 @@ const actionColumn = {
$message.error(e.message) $message.error(e.message)
} }
}, },
onSave: async () => {
try {
const newValue = currentEditRow.value.value
if (isEmpty(newValue)) {
$message.error(i18n.t('dialogue.spec_field_required', { key: i18n.t('common.value') }))
return
}
const { success, msg } = await browserStore.updateZSetItem(
props.name,
props.db,
keyName.value,
row.value,
newValue,
currentEditRow.value.score,
)
if (success) {
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
currentEditRow.value.no = 0
}
},
onCancel: cancelEdit,
}) })
}, },
} }
const columns = reactive([
const columns = computed(() => {
if (!inEdit.value) {
return [
{ {
key: 'no', key: 'no',
title: '#', title: '#',
width: 80, width: 80,
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
render: (row, index) => {
return index + 1
},
}, },
valueColumn, valueColumn,
scoreColumn, scoreColumn,
actionColumn, actionColumn,
]) ]
} else {
const tableData = computed(() => { return [
const data = [] {
if (!isEmpty(props.value)) { key: 'no',
let index = 0 title: '#',
for (const elem of props.value) { width: 80,
data.push({ align: 'center',
no: ++index, titleAlign: 'center',
value: elem.value, render: (row, index) => {
score: elem.score, if (index + 1 === currentEditRow.no) {
}) // editing row, show edit state
return h(NIcon, { size: 16, color: 'red' }, () => h(Edit, { strokeWidth: 5 }))
} else {
return index + 1
} }
},
},
valueColumn,
]
} }
return data
}) })
const entries = computed(() => { const entries = computed(() => {
const len = size(tableData.value) const len = size(props.value)
return `${len} / ${Math.max(len, props.length)}` return `${len} / ${Math.max(len, props.length)}`
}) })
@ -306,10 +325,14 @@ const onUpdateFilter = (filters, sourceColumn) => {
} }
} }
const onFormatChanged = (selDecode, selFormat) => {
emit('reload', selDecode, selFormat)
}
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
cancelEdit() resetEdit()
}, },
}) })
</script> </script>
@ -317,6 +340,7 @@ defineExpose({
<template> <template>
<div class="content-wrapper flex-box-v"> <div class="content-wrapper flex-box-v">
<content-toolbar <content-toolbar
v-show="!inFullEdit"
:db="props.db" :db="props.db"
:key-code="props.keyCode" :key-code="props.keyCode"
:key-path="props.keyPath" :key-path="props.keyPath"
@ -328,7 +352,7 @@ defineExpose({
@delete="emit('delete')" @delete="emit('delete')"
@reload="emit('reload')" @reload="emit('reload')"
@rename="emit('rename')" /> @rename="emit('rename')" />
<div class="tb2 value-item-part flex-box-h"> <div v-show="!inFullEdit" class="tb2 value-item-part flex-box-h">
<div class="flex-box-h"> <div class="flex-box-h">
<n-input-group> <n-input-group>
<n-select <n-select
@ -374,13 +398,14 @@ defineExpose({
{{ $t('interface.add_row') }} {{ $t('interface.add_row') }}
</n-button> </n-button>
</div> </div>
<div class="value-wrapper value-item-part flex-box-v flex-item-expand"> <div class="value-wrapper value-item-part flex-box-h flex-item-expand">
<!-- table -->
<n-data-table <n-data-table
:key="(row) => row.no" v-show="!inFullEdit"
:bordered="false" :bordered="false"
:bottom-bordered="false" :bottom-bordered="false"
:columns="columns" :columns="columns"
:data="tableData" :data="props.value"
:loading="props.loading" :loading="props.loading"
:single-column="true" :single-column="true"
:single-line="false" :single-line="false"
@ -390,12 +415,33 @@ defineExpose({
striped striped
virtual-scroll virtual-scroll
@update:filters="onUpdateFilter" /> @update:filters="onUpdateFilter" />
<!-- edit pane -->
<content-entry-editor
v-show="inEdit"
v-model:fullscreen="fullEdit"
:decode="currentEditRow.decode"
:field="currentEditRow.score"
:field-label="$t('interface.score')"
:format="currentEditRow.format"
:value="currentEditRow.value"
:value-label="$t('common.value')"
class="flex-item-expand"
style="width: 100%"
@close="resetEdit"
@save="saveEdit" />
</div> </div>
<div class="value-footer flex-box-h"> <div class="value-footer flex-box-h">
<n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text> <n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text>
<n-divider v-if="!isNaN(props.length)" vertical /> <n-divider v-if="!isNaN(props.length)" vertical />
<n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text> <n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text>
<div class="flex-item-expand"></div> <div class="flex-item-expand"></div>
<format-selector
v-show="!inEdit"
:decode="props.decode"
:disabled="inEdit"
:format="props.format"
@format-changed="onFormatChanged" />
</div> </div>
</div> </div>
</template> </template>

View File

@ -95,9 +95,9 @@ const onAdd = async () => {
{ {
let data let data
if (newForm.opType === 1) { if (newForm.opType === 1) {
data = await browserStore.prependListItem(server, db, keyName, value) data = await browserStore.prependListItem({ server, db, key: keyName, values: value })
} else { } else {
data = await browserStore.appendListItem(server, db, keyName, value) data = await browserStore.appendListItem({ server, db, key: keyName, values: value })
} }
const { success, msg } = data const { success, msg } = data
if (success) { if (success) {

View File

@ -35,9 +35,9 @@ async function setupApp() {
} catch (e) {} } catch (e) {}
}) })
} }
app.config.warnHandler = (message) => { // app.config.warnHandler = (message) => {
console.warn(message) // console.warn(message)
} // }
app.mount('#app') app.mount('#app')
} }

View File

@ -6,6 +6,7 @@ import {
isEmpty, isEmpty,
join, join,
last, last,
map,
remove, remove,
set, set,
size, size,
@ -1082,21 +1083,21 @@ const useBrowserStore = defineStore('browser', {
/** /**
* remove hash field * remove hash field
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string} key * @param {string|number[]} key
* @param {string} field * @param {string} field
* @returns {Promise<{[msg]: {}, success: boolean, [removed]: string[]}>} * @returns {Promise<{[msg]: {}, success: boolean, [removed]: string[]}>}
*/ */
async removeHashField(connName, db, key, field) { async removeHashField(server, db, key, field) {
try { try {
const { data, success, msg } = await SetHashValue(connName, db, key, field, '', '') const { data, success, msg } = await SetHashValue({ server, db, key, field, newField: '' })
if (success) { if (success) {
const { removed = [] } = data const { removed = [] } = data
if (!isEmpty(removed)) { // if (!isEmpty(removed)) {
const tab = useTabStore() // const tab = useTabStore()
tab.removeValueEntries({ server: connName, db, key, type: 'hash', entries: removed }) // tab.removeValueEntries({ server, db, key, type: 'hash', entries: removed })
} // }
return { success, removed } return { success, removed }
} else { } else {
return { success, msg } return { success, msg }
@ -1125,25 +1126,27 @@ const useBrowserStore = defineStore('browser', {
/** /**
* prepend item to head of list * prepend item to head of list
* @param connName * @param {string} server
* @param db * @param {number} db
* @param key * @param {string|number[]} key
* @param values * @param {string[]} values
* @returns {Promise<{[msg]: string, success: boolean, [item]: []}>} * @returns {Promise<{[msg]: string, success: boolean, [item]: []}>}
*/ */
async prependListItem(connName, db, key, values) { async prependListItem({ server, db, key, values }) {
try { try {
const { data, success, msg } = await AddListItem(connName, db, key, 0, values) const { data, success, msg } = await AddListItem(server, db, key, 0, values)
if (success) { if (success) {
const { left = [] } = data const { left = [] } = data
if (!isEmpty(left)) { if (!isEmpty(left)) {
// TODO: convert to display value
const entries = map(left, (v) => ({ v }))
const tab = useTabStore() const tab = useTabStore()
tab.upsertValueEntries({ tab.upsertValueEntries({
server: connName, server: server,
db, db,
key, key,
type: 'list', type: 'list',
entries: right, entries,
prepend: true, prepend: true,
}) })
} }
@ -1158,25 +1161,26 @@ const useBrowserStore = defineStore('browser', {
/** /**
* append item to tail of list * append item to tail of list
* @param connName * @param {string} server
* @param db * @param {number} db
* @param key * @param {string|number[]} key
* @param values * @param {string[]} values
* @returns {Promise<{[msg]: string, success: boolean, [item]: any[]}>} * @returns {Promise<{[msg]: string, success: boolean, [item]: any[]}>}
*/ */
async appendListItem(connName, db, key, values) { async appendListItem({ server, db, key, values }) {
try { try {
const { data, success, msg } = await AddListItem(connName, db, key, 1, values) const { data, success, msg } = await AddListItem(server, db, key, 1, values)
if (success) { if (success) {
const { right = [] } = data const { right = [] } = data
if (!isEmpty(right)) { if (!isEmpty(right)) {
const entries = map(right, (v) => ({ v }))
const tab = useTabStore() const tab = useTabStore()
tab.upsertValueEntries({ tab.upsertValueEntries({
server: connName, server: server,
db, db,
key, key,
type: 'list', type: 'list',
entries: right, entries,
prepend: false, prepend: false,
}) })
} }
@ -1196,8 +1200,8 @@ const useBrowserStore = defineStore('browser', {
* @param {string|number[]} key * @param {string|number[]} key
* @param {number} index * @param {number} index
* @param {string|number[]} value * @param {string|number[]} value
* @param {string} decode * @param {decodeTypes} decode
* @param {string} format * @param {formatTypes} format
* @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>} * @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>}
*/ */
async updateListItem({ server, db, key, index, value, decode = decodeTypes.NONE, format = formatTypes.RAW }) { async updateListItem({ server, db, key, index, value, decode = decodeTypes.NONE, format = formatTypes.RAW }) {
@ -1237,16 +1241,16 @@ const useBrowserStore = defineStore('browser', {
const { data, success, msg } = await SetListItem({ server, db, key, index }) const { data, success, msg } = await SetListItem({ server, db, key, index })
if (success) { if (success) {
const { removed = [] } = data const { removed = [] } = data
if (!isEmpty(removed)) { // if (!isEmpty(removed)) {
const tab = useTabStore() // const tab = useTabStore()
tab.removeValueEntries({ // tab.removeValueEntries({
server, // server,
db, // db,
key, // key,
type: 'list', // type: 'list',
entries: removed, // entries: removed,
}) // })
} // }
return { success, removed } return { success, removed }
} else { } else {
return { success, msg } return { success, msg }
@ -1311,18 +1315,18 @@ const useBrowserStore = defineStore('browser', {
/** /**
* remove item from set * remove item from set
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} value * @param {string} value
* @returns {Promise<{[msg]: string, success: boolean}>} * @returns {Promise<{[msg]: string, success: boolean}>}
*/ */
async removeSetItem(connName, db, key, value) { async removeSetItem(server, db, key, value) {
try { try {
const { success, msg } = await SetSetItem(connName, db, key, true, [value]) const { success, msg } = await SetSetItem(server, db, key, true, [value])
if (success) { if (success) {
const tab = useTabStore() // const tab = useTabStore()
tab.removeValueEntries({ server: connName, db, key, type: 'set', entries: [value] }) // tab.removeValueEntries({ server: connName, db, key, type: 'set', entries: [value] })
return { success } return { success }
} else { } else {
return { success, msg } return { success, msg }
@ -1358,26 +1362,46 @@ const useBrowserStore = defineStore('browser', {
/** /**
* update item of sorted set * update item of sorted set
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} value * @param {string} value
* @param {string} newValue * @param {string} newValue
* @param {number} score * @param {number} score
* @param {decodeTypes} decode
* @param {formatTypes} format
* @returns {Promise<{[msg]: string, success: boolean, [updated]: {}, [removed]: []}>} * @returns {Promise<{[msg]: string, success: boolean, [updated]: {}, [removed]: []}>}
*/ */
async updateZSetItem(connName, db, key, value, newValue, score) { async updateZSetItem({
server,
db,
key,
value = '',
newValue,
score,
decode = decodeTypes.NONE,
format = formatTypes.RAW,
}) {
try { try {
const { data, success, msg } = await UpdateZSetValue(connName, db, key, value, newValue, score) const { data, success, msg } = await UpdateZSetValue({
server,
db,
key,
value,
newValue,
score,
decode,
format,
})
if (success) { if (success) {
const { updated, removed } = data const { updated, removed } = data
const tab = useTabStore() // const tab = useTabStore()
if (!isEmpty(updated)) { // if (!isEmpty(updated)) {
tab.upsertValueEntries({ server: connName, db, key, type: 'zset', entries: updated }) // tab.upsertValueEntries({ server, db, key, type: 'zset', entries: updated })
} // }
if (!isEmpty(removed)) { // if (!isEmpty(removed)) {
tab.removeValueEntries({ server: connName, db, key, type: 'zset', entries: removed }) // tab.removeValueEntries({ server, db, key, type: 'zset', entries: removed })
} // }
return { success, updated, removed } return { success, updated, removed }
} else { } else {
return { success, msg } return { success, msg }
@ -1389,22 +1413,22 @@ const useBrowserStore = defineStore('browser', {
/** /**
* remove item from sorted set * remove item from sorted set
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} value * @param {string} value
* @returns {Promise<{[msg]: string, success: boolean, [removed]: []}>} * @returns {Promise<{[msg]: string, success: boolean, [removed]: []}>}
*/ */
async removeZSetItem(connName, db, key, value) { async removeZSetItem(server, db, key, value) {
try { try {
const { data, success, msg } = await UpdateZSetValue(connName, db, key, value, '', 0) const { data, success, msg } = await UpdateZSetValue({ server, db, key, value, newValue: '', score: 0 })
if (success) { if (success) {
const { removed } = data const { removed } = data
if (!isEmpty(removed)) { // if (!isEmpty(removed)) {
const tab = useTabStore() // const tab = useTabStore()
tab.removeValueEntries({ server: connName, db, key, type: 'zset', entries: removed }) // tab.removeValueEntries({ server: server, db, key, type: 'zset', entries: removed })
} // }
return { success } return { success, removed }
} else { } else {
return { success, msg } return { success, msg }
} }