All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cds.jdbc.h2.H2SqlMapping Maven / Gradle / Ivy

The newest version!
/*******************************************************************
 * © 2024 SAP SE or an SAP affiliate company. All rights reserved. *
 *******************************************************************/
package com.sap.cds.jdbc.h2;

import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sap.cds.CdsDataStoreException;
import com.sap.cds.impl.sql.SQLHelper;
import com.sap.cds.impl.sql.SqlMappingImpl;
import com.sap.cds.reflect.CdsStructuredType;

public class H2SqlMapping extends SqlMappingImpl {

	private static final Pattern PATTERN = Pattern.compile("([^.|\\[\\d+\\]]+)|(\\d+)"); // group path segments and array index

	public H2SqlMapping(CdsStructuredType rowType, Function casing) {
		super(rowType, casing);
	}

	@Override
	public String jsonQuery(String column, String jsonPath) {
		if (!jsonPath.startsWith("$.")) {
			throw new CdsDataStoreException("Unsupported JSON path: '" + jsonPath + "' must start with '$.'");
		}
		jsonPath = jsonPath.substring(2);

		Matcher matcher = PATTERN.matcher(jsonPath);
		StringBuilder sb = new StringBuilder();
		int lastEnd = 0;

		while (matcher.find()) {
			sb.append(jsonPath, lastEnd, matcher.start());
			if (matcher.group(1) != null) {
				// quote the segment
				sb.append(SQLHelper.delimited(matcher.group(1)));
			} else if (matcher.group(2) != null) {
				// increment the index
				sb.append(Integer.parseInt(matcher.group(2)) + 1);
			}
			lastEnd = matcher.end();
		}
		sb.append(jsonPath, lastEnd, jsonPath.length());

		return "(" + column + ")." + sb.toString();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy