Skip to content

Commit

Permalink
fixed error generating rdb: improve view table alias generation (#3174)
Browse files Browse the repository at this point in the history
Co-authored-by: Stefano Ricci <[email protected]>
  • Loading branch information
SteRiccio and SteRiccio authored Dec 4, 2023
1 parent 3e608ec commit f99ba3e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 16 additions & 2 deletions common/model/db/sql/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as StringUtils from '@core/stringUtils'

export const types = {
uuid: 'UUID',
varchar: 'VARCHAR',
Expand All @@ -9,13 +11,25 @@ export const types = {
geometryPoint: 'geometry(Point)',
}

// Alias
/**
* Generates an alias from the specified name, splitting it into words
* and getting the first letter of each word, to make it more or less human readable,
* followed by a short hash of the name, to make it (almost) unique, but still short.
*
* @param {!string} name - The name used to generate the alias.
* @returns {string} - The generated alias.
*/
export const createAlias = (name) =>
// add '_' prefix to avoid collision with reserved words
`_${name
// split in words
.split('_')
// get first letters of each word
.map((word) => word[0])
.join('')}`
.join('')}_${
// append name hash to avoid collisions
StringUtils.hashCode(name)
}`

export const addAlias = (alias, ...columnNames) => columnNames.map((columnName) => `${alias}.${columnName}`)

Expand Down
14 changes: 14 additions & 0 deletions core/stringUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,17 @@ export const removePrefix = (prefix) => (text) => (text.startsWith(prefix) ? tex
export const removeSuffix = (suffix) => (text) => text.substring(0, text.length - suffix.length)

export const quote = (text) => (isBlank(text) ? '' : `'${text}'`)

export const hashCode = (str) => {
let hash = 0
if (typeof str !== 'string' || str.length === 0) {
return String(hash)
}
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = (hash << 5) - hash + char
hash = hash & hash // convert to 32bit integer
}
hash = hash >>> 0 // convert signed to unsigned https://stackoverflow.com/a/1908655
return Number(hash).toString(32).toUpperCase() // make the hash small, convert base10 to base32
}

0 comments on commit f99ba3e

Please sign in to comment.