sql-util.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { A_Const, A_Expr, ColumnRef, CreatePolicyStmt, Node, parseQuery } from 'libpg-query/wasm'
  2. export type PolicyInfo = {
  3. name: string
  4. relation: string
  5. command?: string
  6. roles: string[]
  7. usingNode?: Node
  8. withCheckNode?: Node
  9. }
  10. /**
  11. * Extracts keys from a union type.
  12. */
  13. type ExtractKeys<T> = T extends T ? keyof T : never
  14. /**
  15. * Unwraps a Node to get its underlying value.
  16. */
  17. type NodeValue<T extends Node, U extends ExtractKeys<Node>> =
  18. T extends Record<U, infer V> ? V : never
  19. export class AssertionError extends Error {
  20. constructor(message: string) {
  21. super(message)
  22. // Pop the top line from the stack trace so that
  23. // debug tools will reference the code calling the
  24. // assertion function and not this error within it
  25. if (this.stack) {
  26. // Capture the current stack trace and split it into lines
  27. const stackLines = this.stack.split('\n')
  28. // Remove the second line which is the current constructor
  29. stackLines.splice(1, 1)
  30. // Reassign the modified stack trace back to the error object
  31. this.stack = stackLines.join('\n')
  32. }
  33. }
  34. }
  35. /**
  36. * Asserts that a value is defined.
  37. *
  38. * Useful for type narrowing.
  39. */
  40. export function assertDefined<T>(value: T | undefined, errorMessage: string): asserts value is T {
  41. if (value === undefined) {
  42. throw new AssertionError(errorMessage)
  43. }
  44. }
  45. /**
  46. * Asserts that a `Node` is a specific type.
  47. *
  48. * Useful for type narrowing.
  49. */
  50. export function assertNodeType<T extends Node>(
  51. node: Node,
  52. type: ExtractKeys<T>,
  53. errorMessage: string
  54. ): asserts node is T {
  55. if (!(type in node)) {
  56. throw new AssertionError(errorMessage)
  57. }
  58. }
  59. /**
  60. * Asserts that a `Node` is a specific type and
  61. * unwraps its underlying value.
  62. *
  63. * @returns The unwrapped `Node` value.
  64. * @throws If `node` is not of type `type`.
  65. */
  66. export function assertAndUnwrapNode<T extends Node, U extends ExtractKeys<Node>>(
  67. node: Node,
  68. type: U,
  69. errorMessage: string
  70. ): NodeValue<T, U> {
  71. if (!(type in node)) {
  72. throw new AssertionError(errorMessage)
  73. }
  74. return (node as any)[type]
  75. }
  76. /**
  77. * Unwraps a `Node`'s underlying value.
  78. *
  79. * @returns The unwrapped `Node` value or `undefined` if
  80. * the node is not of type `type`.
  81. */
  82. export function unwrapNode<T extends Node, U extends ExtractKeys<Node>>(
  83. node: Node,
  84. type: U
  85. ): NodeValue<T, U> | undefined {
  86. if (!(type in node)) {
  87. return undefined
  88. }
  89. return (node as any)[type]
  90. }
  91. /**
  92. * Asserts that either the left or right side of the
  93. * expression is processed through `fn` without throwing
  94. * any errors.
  95. *
  96. * If both sides throw errors, the assertion fails and the
  97. * error from the left side will be thrown.
  98. */
  99. export function assertEitherSideOfExpression<U>(
  100. expression: A_Expr,
  101. fn: (node: Node, side: 'left' | 'right') => U
  102. ): U {
  103. assertDefined(expression.lexpr, 'Expected left side of expression to exist')
  104. assertDefined(expression.rexpr, 'Expected right side of expression to exist')
  105. try {
  106. return fn(expression.lexpr, 'left')
  107. } catch (leftError) {
  108. try {
  109. return fn(expression.rexpr, 'right')
  110. } catch (rightError) {
  111. throw leftError
  112. }
  113. }
  114. }
  115. /**
  116. * Asserts that both sides of the expression are processed
  117. * without throwing any errors.
  118. *
  119. * Order doesn't matter. As long as `firstFn` and `secondFn`
  120. * pass separately on either side of the expression, the assertion
  121. * will pass. Otherwise if `firstFn` and `secondFn` both fail
  122. * after trying on both sides separately, the assertion will fail.
  123. */
  124. export function assertEachSideOfExpression<U>(
  125. expression: A_Expr,
  126. firstFn: (node: Node) => void,
  127. secondFn: (node: Node) => void
  128. ): void {
  129. assertDefined(expression.lexpr, 'Expected left side of expression to exist')
  130. assertDefined(expression.rexpr, 'Expected right side of expression to exist')
  131. let firstSide: Node
  132. let secondSide: Node
  133. try {
  134. // Try `firstFn` on the left first
  135. firstSide = expression.lexpr
  136. secondSide = expression.rexpr
  137. firstFn(firstSide)
  138. } catch (firstError) {
  139. // Otherwise try `firstFn` on the right
  140. firstSide = expression.rexpr
  141. secondSide = expression.lexpr
  142. try {
  143. firstFn(firstSide)
  144. } catch (secondError) {
  145. // `firstFn` failed on both sides, so we
  146. // need to throw an error not matter what
  147. // Perform one more test using `secondFn`
  148. // to help determine which error to show
  149. // for `firstFn`
  150. try {
  151. secondFn(secondSide)
  152. } catch (_) {
  153. throw firstError
  154. }
  155. throw secondError
  156. }
  157. }
  158. try {
  159. // `firstFn` passed on one of the sides, so
  160. // try `secondFn` on the opposite side
  161. secondFn(secondSide)
  162. } catch (err) {
  163. // `secondFn` failed, so we need to throw an error
  164. throw err
  165. }
  166. }
  167. /**
  168. * Extracts all the `CREATE POLICY` statements
  169. * from a SQL string as parsed ASTs.
  170. */
  171. export async function getPolicies(sql: string) {
  172. const result = await parseQuery(sql)
  173. assertDefined(result.stmts, 'Expected parse result to contain statements')
  174. return result.stmts.reduce<CreatePolicyStmt[]>((filtered, stmt) => {
  175. assertDefined(stmt.stmt, 'Expected statement to exist')
  176. const createPolicyStatement = unwrapNode(stmt.stmt, 'CreatePolicyStmt')
  177. if (createPolicyStatement) {
  178. return [...filtered, createPolicyStatement]
  179. }
  180. return filtered
  181. }, [])
  182. }
  183. /**
  184. * Parses a Postgres SQL policy.
  185. *
  186. * @returns Information about the policy, including its name, table, command, and expressions.
  187. */
  188. export async function getPolicyInfo(createPolicyStatement: CreatePolicyStmt) {
  189. assertDefined(createPolicyStatement.policy_name, 'Expected policy to have a name')
  190. assertDefined(createPolicyStatement.table?.relname, 'Expected policy to have a relation')
  191. const name = createPolicyStatement.policy_name
  192. const relation = createPolicyStatement.table.relname
  193. const command = createPolicyStatement.cmd_name
  194. const roles =
  195. createPolicyStatement.roles?.map((node) => {
  196. const roleSpec = assertAndUnwrapNode(
  197. node,
  198. 'RoleSpec',
  199. 'Expected roles to contain a list of RoleSpec'
  200. )
  201. assertDefined(roleSpec.rolename, 'Expected RoleSpec to have a rolename')
  202. return roleSpec.rolename
  203. }) ?? []
  204. const usingExpression = createPolicyStatement.qual
  205. const checkExpression = createPolicyStatement.with_check
  206. const policyInfo: PolicyInfo = {
  207. name,
  208. relation,
  209. command,
  210. roles,
  211. usingNode: usingExpression,
  212. withCheckNode: checkExpression,
  213. }
  214. return policyInfo
  215. }
  216. export function renderTargets<T>(targets: Node[], renderTarget: (node: Node) => T): T[] {
  217. return targets.map((node) => {
  218. const target = assertAndUnwrapNode(
  219. node,
  220. 'ResTarget',
  221. 'Expected target list to contain ResTargets'
  222. )
  223. assertDefined(target.val, 'Expected ResTarget to have a val')
  224. return renderTarget(target.val)
  225. })
  226. }
  227. export function renderColumn(column: ColumnRef) {
  228. assertDefined(column.fields, 'Expected column to have fields')
  229. return renderFields(column.fields)
  230. }
  231. export function assertAndRenderColumn(node: Node, errorMessage: string) {
  232. const column = assertAndUnwrapNode(node, 'ColumnRef', errorMessage)
  233. return renderColumn(column)
  234. }
  235. export function renderJsonExpression(expression: A_Expr): string {
  236. assertDefined(expression.name, 'Expected expression to have an operator')
  237. if (expression.name.length > 1) {
  238. throw new AssertionError('Only one JSON operator supported per expression')
  239. }
  240. const [name] = expression.name
  241. const operatorString = assertAndUnwrapNode(
  242. name,
  243. 'String',
  244. 'Expected JSON operator to be a string'
  245. )
  246. assertDefined(operatorString.sval, 'PG string expected to have an sval')
  247. const operator = operatorString.sval
  248. if (!['->', '->>'].includes(operator)) {
  249. throw new AssertionError(`Invalid JSON operator ${operator}`)
  250. }
  251. assertDefined(expression.lexpr, 'Expected JSON expression to have a left-side component')
  252. assertDefined(expression.rexpr, 'Expected JSON expression to have a right-side component')
  253. let left: string | number
  254. let right: string | number
  255. const leftConstant = unwrapNode(expression.lexpr, 'A_Const')
  256. const leftColumn = unwrapNode(expression.lexpr, 'ColumnRef')
  257. const leftFuncCall = unwrapNode(expression.lexpr, 'FuncCall')
  258. const leftExpression = unwrapNode(expression.lexpr, 'A_Expr')
  259. if (leftConstant) {
  260. // JSON path cannot contain a float
  261. if ('fval' in leftConstant) {
  262. throw new AssertionError('Invalid JSON path: Expression cannot contain a float')
  263. }
  264. left = `'${parseConstant(leftConstant)}'`
  265. } else if (leftColumn) {
  266. left = renderColumn(leftColumn)
  267. } else if (leftFuncCall) {
  268. assertDefined(leftFuncCall.funcname, 'Expected function call to have a name')
  269. const functionName = renderFields(leftFuncCall.funcname)
  270. left = `${functionName}()`
  271. } else if (leftExpression) {
  272. left = renderJsonExpression(leftExpression)
  273. } else {
  274. throw new AssertionError('Invalid JSON path')
  275. }
  276. const rightConstant = unwrapNode(expression.rexpr, 'A_Const')
  277. if (rightConstant) {
  278. // JSON path cannot contain a float
  279. if ('fval' in rightConstant) {
  280. throw new AssertionError('Invalid JSON path: Expression cannot contain a float')
  281. }
  282. right = `'${parseConstant(rightConstant)}'`
  283. } else {
  284. throw new AssertionError('Invalid JSON path')
  285. }
  286. return `${left}${operator}${right}`
  287. }
  288. export function renderFields(fields: Node[]) {
  289. const nameSegments = fields
  290. .map((field) => {
  291. const stringField = unwrapNode(field, 'String')
  292. const starField = unwrapNode(field, 'A_Star')
  293. if (stringField !== undefined) {
  294. return stringField.sval
  295. } else if (starField !== undefined) {
  296. return '*'
  297. } else {
  298. const [internalType] = Object.keys(field)
  299. throw new Error(`Unsupported internal type '${internalType}' for fields`)
  300. }
  301. })
  302. .filter((name): name is string => name !== undefined)
  303. return nameSegments.join('.')
  304. }
  305. export function parseConstant(constant: A_Const) {
  306. if ('sval' in constant) {
  307. return constant.sval?.sval ?? ''
  308. } else if ('ival' in constant) {
  309. // The PG parser turns 0 into undefined, so convert it back here
  310. return constant.ival?.ival ?? 0
  311. } else if ('fval' in constant) {
  312. return constant.fval?.fval ? parseFloat(constant.fval.fval) : 0
  313. } else {
  314. throw new AssertionError(`Constant values must be a string, integer, or float`)
  315. }
  316. }