From 566bf0f3f7ef5b9766e95253beb4a66bb67f249d Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Wed, 18 Apr 2018 11:01:07 +0200 Subject: [PATCH 01/15] Added MBTiles support for iOS and Android --- index.d.ts | 395 +--- index.js | 16 +- .../android/react/maps/AirMapMbTile.java | 139 ++ .../react/maps/AirMapMbTileManager.java | 56 + .../airbnb/android/react/maps/AirMapView.java | 186 +- .../android/react/maps/MapsPackage.java | 2 + lib/components/MapMbTile.js | 71 + lib/components/MapView.js | 63 +- lib/ios/AirMaps.xcodeproj/project.pbxproj | 49 + lib/ios/AirMaps/AIRMap.m | 41 +- lib/ios/AirMaps/AIRMapManager.m | 77 +- lib/ios/AirMaps/AIRMapMbTile.h | 47 + lib/ios/AirMaps/AIRMapMbTile.m | 68 + lib/ios/AirMaps/AIRMapMbTileManager.h | 14 + lib/ios/AirMaps/AIRMapMbTileManager.m | 40 + lib/ios/AirMaps/AIRMapMbTileOverlay.h | 15 + lib/ios/AirMaps/AIRMapMbTileOverlay.m | 40 + lib/ios/AirMaps/fmdb/FMDB.h | 10 + lib/ios/AirMaps/fmdb/FMDatabase.h | 1360 ++++++++++++++ lib/ios/AirMaps/fmdb/FMDatabase.m | 1596 +++++++++++++++++ lib/ios/AirMaps/fmdb/FMDatabaseAdditions.h | 250 +++ lib/ios/AirMaps/fmdb/FMDatabaseAdditions.m | 245 +++ lib/ios/AirMaps/fmdb/FMDatabasePool.h | 258 +++ lib/ios/AirMaps/fmdb/FMDatabasePool.m | 316 ++++ lib/ios/AirMaps/fmdb/FMDatabaseQueue.h | 235 +++ lib/ios/AirMaps/fmdb/FMDatabaseQueue.m | 270 +++ lib/ios/AirMaps/fmdb/FMResultSet.h | 467 +++++ lib/ios/AirMaps/fmdb/FMResultSet.m | 432 +++++ 28 files changed, 6161 insertions(+), 597 deletions(-) mode change 100644 => 100755 index.d.ts mode change 100644 => 100755 index.js create mode 100644 lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java create mode 100644 lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTileManager.java mode change 100644 => 100755 lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java mode change 100644 => 100755 lib/android/src/main/java/com/airbnb/android/react/maps/MapsPackage.java create mode 100644 lib/components/MapMbTile.js mode change 100644 => 100755 lib/components/MapView.js mode change 100644 => 100755 lib/ios/AirMaps/AIRMap.m mode change 100644 => 100755 lib/ios/AirMaps/AIRMapManager.m create mode 100644 lib/ios/AirMaps/AIRMapMbTile.h create mode 100644 lib/ios/AirMaps/AIRMapMbTile.m create mode 100644 lib/ios/AirMaps/AIRMapMbTileManager.h create mode 100644 lib/ios/AirMaps/AIRMapMbTileManager.m create mode 100644 lib/ios/AirMaps/AIRMapMbTileOverlay.h create mode 100644 lib/ios/AirMaps/AIRMapMbTileOverlay.m create mode 100644 lib/ios/AirMaps/fmdb/FMDB.h create mode 100644 lib/ios/AirMaps/fmdb/FMDatabase.h create mode 100644 lib/ios/AirMaps/fmdb/FMDatabase.m create mode 100644 lib/ios/AirMaps/fmdb/FMDatabaseAdditions.h create mode 100644 lib/ios/AirMaps/fmdb/FMDatabaseAdditions.m create mode 100755 lib/ios/AirMaps/fmdb/FMDatabasePool.h create mode 100755 lib/ios/AirMaps/fmdb/FMDatabasePool.m create mode 100755 lib/ios/AirMaps/fmdb/FMDatabaseQueue.h create mode 100755 lib/ios/AirMaps/fmdb/FMDatabaseQueue.m create mode 100644 lib/ios/AirMaps/fmdb/FMResultSet.h create mode 100644 lib/ios/AirMaps/fmdb/FMResultSet.m diff --git a/index.d.ts b/index.d.ts old mode 100644 new mode 100755 index 044c05082..ffe37a8ce --- a/index.d.ts +++ b/index.d.ts @@ -1,164 +1,27 @@ declare module "react-native-maps" { - import * as React from 'react'; - import { - Animated, - ImageRequireSource, - ImageURISource, - NativeSyntheticEvent, - ViewProperties - } from 'react-native'; - + export interface Region { - latitude: number; - longitude: number; - latitudeDelta: number; - longitudeDelta: number; + latitude: number + longitude: number + latitudeDelta: number + longitudeDelta: number } - + export interface LatLng { - latitude: number; - longitude: number; + latitude: number + longitude: number } export interface Point { - x: number; - y: number; - } - - // helper interface - export interface MapEvent extends NativeSyntheticEvent {} - - export type LineCapType = 'butt' | 'round' | 'square'; - export type LineJoinType = 'miter' | 'round' | 'bevel'; - - // ======================================================================= - // AnimatedRegion - // ======================================================================= - - interface AnimatedRegionTimingConfig extends Animated.AnimationConfig, Partial { - easing?: (value: number) => number; - duration?: number; - delay?: number; - } - - interface AnimatedRegionSpringConfig extends Animated.AnimationConfig, Partial { - overshootClamping?: boolean; - restDisplacementThreshold?: number; - restSpeedThreshold?: number; - velocity?: number | Point; - bounciness?: number; - speed?: number; - tension?: number; - friction?: number; - stiffness?: number; - mass?: number; - damping?: number; - } - - export class AnimatedRegion extends Animated.AnimatedWithChildren { - latitude: Animated.Value - longitude: Animated.Value - latitudeDelta: Animated.Value - longitudeDelta: Animated.Value - - constructor(region?: Region); - - setValue(value: Region): void; - setOffset(offset: Region): void; - flattenOffset(): void; - stopAnimation(callback?: (region: Region) => void): void; - addListener(callback: (region: Region) => void): string; - removeListener(id: string): void; - spring(config: AnimatedRegionSpringConfig): Animated.CompositeAnimation; - timing(config: AnimatedRegionTimingConfig): Animated.CompositeAnimation; - } - - // ======================================================================= - // MapView (default export) - // ======================================================================= - - /** - * takeSnapshot options - */ - export interface SnapshotOptions { - /** optional, when omitted the view-width is used */ - width?: number; - /** optional, when omitted the view-height is used */ - height?: number; - /** __iOS only__, optional region to render */ - region?: Region; - /** image formats, defaults to 'png' */ - format?: 'png' | 'jpg'; - /** image quality: 0..1 (only relevant for jpg, default: 1) */ - quality?: number; - /** result types, defaults to 'file' */ - result?: 'file' | 'base64'; - } - - /** - * onUserLocationChange parameters - */ - export interface EventUserLocation extends NativeSyntheticEvent<{}> { - nativeEvent: { - coordinate: { - latitude: number, - longitude: number, - altitude: number, - accuracy: number, - speed: number, - isFromMockProvider: boolean, - }, - }; - } - - /** - * Map style elements. - * @see https://developers.google.com/maps/documentation/ios-sdk/styling#use_a_string_resource - * @see https://developers.google.com/maps/documentation/android-api/styling - */ - export type MapStyleElement = { - featureType?: string, - elementType?: string, - stylers: object[], - }; - - export type EdgePadding = { - top: Number, - right: Number, - bottom: Number, - left: Number, - }; - - export type EdgeInsets = { - top: Number, - right: Number, - bottom: Number, - left: Number, - }; - - export type KmlMarker = { - id: String, - title: String, - description: String, - coordinate: LatLng, - position: Point, - }; - - /** - * onKmlReady parameter - */ - export interface KmlMapEvent extends NativeSyntheticEvent<{ markers: KmlMarker[] }> { + x: number + y: number } - type MapTypes = 'standard' | 'satellite' | 'hybrid' | 'terrain' | 'none' | 'mutedStandard'; - - export interface MapViewProps extends ViewProperties { - provider?: 'google' | null; - customMapStyle?: MapStyleElement[]; + export interface MapViewProps { + provider?: 'google'; + style: any; + customMapStyle?: any[]; customMapStyleString?: string; showsUserLocation?: boolean; userLocationAnnotationTitle?: string; @@ -171,8 +34,8 @@ declare module "react-native-maps" { rotateEnabled?: boolean; cacheEnabled?: boolean; loadingEnabled?: boolean; - loadingBackgroundColor?: string; - loadingIndicatorColor?: string; + loadingBackgroundColor?: any; + loadingIndicatorColor?: any; scrollEnabled?: boolean; pitchEnabled?: boolean; toolbarEnabled?: boolean; @@ -182,129 +45,84 @@ declare module "react-native-maps" { showsTraffic?: boolean; showsIndoors?: boolean; showsIndoorLevelPicker?: boolean; - mapType?: MapTypes; - region?: Region; - initialRegion?: Region; + mapType?: 'standard' | 'satellite' | 'hybrid' | 'terrain' | 'none' | 'mutedStandard'; + region?: { latitude: number; longitude: number; latitudeDelta: number; longitudeDelta: number; }; + initialRegion?: { latitude: number; longitude: number; latitudeDelta: number; longitudeDelta: number; }; liteMode?: boolean; - mapPadding?: EdgePadding; maxDelta?: number; minDelta?: number; - legalLabelInsets?: EdgeInsets; - - onMapReady?: () => void; - onKmlReady?: (values: KmlMapEvent) => void; + legalLabelInsets?: any; + onChange?: Function; + onMapReady?: Function; onRegionChange?: (region: Region) => void; onRegionChangeComplete?: (region: Region) => void; - onPress?: (event: MapEvent) => void; - onLongPress?: (event: MapEvent) => void; - onUserLocationChange?: (event: EventUserLocation) => void; - onPanDrag?: (event: MapEvent) => void; - onPoiClick?: (event: MapEvent<{ placeId: string, name: string }>) => void; - onMarkerPress?: (event: MapEvent<{ action: 'marker-press', id: string }>) => void; - onMarkerSelect?: (event: MapEvent<{ action: 'marker-select', id: string }>) => void; - onMarkerDeselect?: (event: MapEvent<{ action: 'marker-deselect', id: string }>) => void; - onCalloutPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; - onMarkerDragStart?: (event: MapEvent) => void; - onMarkerDrag?: (event: MapEvent) => void; - onMarkerDragEnd?: (event: MapEvent) => void; - + onPress?: (value: { coordinate: LatLng, position: Point }) => void; + onLayout?: Function; + onLongPress?: (value: { coordinate: LatLng, position: Point }) => void; + onPanDrag?: (value: {coordinate: LatLng, position: Point }) => void; + onMarkerPress?: Function; + onMarkerSelect?: Function; + onMarkerDeselect?: Function; + onCalloutPress?: Function; + onMarkerDragStart?: (value: { coordinate: LatLng, position: Point }) => void; + onMarkerDrag?: (value: { coordinate: LatLng, position: Point }) => void; + onMarkerDragEnd?: (value: { coordinate: LatLng, position: Point }) => void; minZoomLevel?: number; maxZoomLevel?: number; - kmlSrc?: string; } export default class MapView extends React.Component { + static Animated: any; + static AnimatedRegion: any; animateToRegion(region: Region, duration?: number): void; animateToCoordinate(latLng: LatLng, duration?: number): void; animateToBearing(bearing: number, duration?: number): void; animateToViewingAngle(angle: number, duration?: number): void; fitToElements(animated: boolean): void; fitToSuppliedMarkers(markers: string[], animated: boolean): void; - fitToCoordinates(coordinates?: LatLng[], options?: { edgePadding?: EdgePadding, animated?: boolean }): void; + fitToCoordinates(coordinates?: LatLng[], options?:{}): void; setMapBoundaries(northEast: LatLng, southWest: LatLng): void; - takeSnapshot(options?: SnapshotOptions): Promise; } - export class MapViewAnimated extends MapView { - } - - // ======================================================================= - // Marker - // ======================================================================= + export type LineCapType = 'butt' | 'round' | 'square'; + export type LineJoinType = 'miter' | 'round' | 'bevel'; - export interface MarkerProps extends ViewProperties { + export interface MarkerProps { identifier?: string; reuseIdentifier?: string; title?: string; description?: string; - image?: ImageURISource | ImageRequireSource; + image?: any; opacity?: number; pinColor?: string; - coordinate: LatLng | AnimatedRegion; - centerOffset?: Point; - calloutOffset?: Point; - anchor?: Point; - calloutAnchor?: Point; + coordinate: { latitude: number; longitude: number }; + centerOffset?: { x: number; y: number }; + calloutOffset?: { x: number; y: number }; + anchor?: { x: number; y: number }; + calloutAnchor?: { x: number; y: number }; flat?: boolean; draggable?: boolean; + onPress?: (value: { coordinate: LatLng, position: Point }) => void; + onSelect?: (value: { coordinate: LatLng, position: Point }) => void; + onDeselect?: (value: { coordinate: LatLng, position: Point }) => void; + onCalloutPress?: Function; + onDragStart?: (value: { coordinate: LatLng, position: Point }) => void; + onDrag?: (value: { coordinate: LatLng, position: Point }) => void; + onDragEnd?: (value: { coordinate: LatLng, position: Point }) => void; + zIndex?: number; + style?: any; + rotation?: number; tracksViewChanges?: boolean tracksInfoWindowChanges?: boolean - stopPropagation?: boolean - onPress?: (event: MapEvent<{ action: 'marker-press', id: string }>) => void; - onSelect?: (event: MapEvent<{ action: 'marker-select', id: string }>) => void; - onDeselect?: (event: MapEvent<{ action: 'marker-deselect', id: string }>) => void; - onCalloutPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; - onDragStart?: (event: MapEvent) => void; - onDrag?: (event: MapEvent) => void; - onDragEnd?: (event: MapEvent) => void; - - rotation?: number; - zIndex?: number; - } - - export class Marker extends React.Component { - /** - * Shows the callout for this marker - */ - showCallout(): void; - /** - * Hides the callout for this marker - */ - hideCallout(): void; - /** - * Animates marker movement. - * __Android only__ - */ - animateMarkerToCoordinate(coordinate: LatLng, duration?: number): void; - } - - export class MarkerAnimated extends Marker { - } - - // ======================================================================= - // Callout - // ======================================================================= - - export interface MapCalloutProps extends ViewProperties { - tooltip?: boolean; - onPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; } - export class Callout extends React.Component { - } - - // ======================================================================= - // Polyline - // ======================================================================= - - export interface MapPolylineProps extends ViewProperties { - coordinates: LatLng[]; - onPress?: (event: MapEvent) => void; + export interface MapPolylineProps { + coordinates: { latitude: number; longitude: number; }[]; + onPress?: Function; tappable?: boolean; fillColor?: string; strokeWidth?: number; strokeColor?: string; - strokeColors?: string[]; zIndex?: number; lineCap?: LineCapType; lineJoin?: LineJoinType; @@ -314,17 +132,10 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export class Polyline extends React.Component { - } - - // ======================================================================= - // Polygon - // ======================================================================= - - export interface MapPolygonProps extends ViewProperties { - coordinates: LatLng[]; - holes?: LatLng[][]; - onPress?: (event: MapEvent) => void; + export interface MapPolygonProps { + coordinates: { latitude: number; longitude: number; }[]; + holes?: { latitude: number; longitude: number; }[][]; + onPress?: Function; tappable?: boolean; strokeWidth?: number; strokeColor?: string; @@ -338,17 +149,10 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export class Polygon extends React.Component { - } - - // ======================================================================= - // Circle - // ======================================================================= - - export interface MapCircleProps extends ViewProperties { - center: LatLng; + export interface MapCircleProps { + center: { latitude: number; longitude: number }; radius: number; - onPress?: (event: MapEvent) => void; + onPress?: Function; strokeWidth?: number; strokeColor?: string; fillColor?: string; @@ -360,62 +164,39 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export class Circle extends React.Component { - } - - // ======================================================================= - // UrlTile & LocalTile - // ======================================================================= - - export interface MapUrlTileProps extends ViewProperties { + export interface MapUrlTileProps { urlTemplate: string; - maximumZ?: number; zIndex?: number; } - export class UrlTile extends React.Component { - } - - export interface MapLocalTileProps extends ViewProperties { + export interface MapLocalTileProps { pathTemplate: string; - tileSize?: number; + tileSize: number; zIndex?: number; } - export class LocalTile extends React.Component { - } - - // ======================================================================= - // Overlay - // ======================================================================= - - type Coordinate = [number, number] - - export interface MapOverlayProps extends ViewProperties { - image?: ImageURISource | ImageRequireSource; - bounds: [Coordinate, Coordinate]; - } - - export class Overlay extends React.Component { - } - - export class OverlayAnimated extends Overlay { + export interface MapMbTileProps { + pathTemplate: string; + tileSize: number; + zIndex?: number; } - // ======================================================================= - // Constants - // ======================================================================= - - export const MAP_TYPES: { - STANDARD: MapTypes, - SATELLITE: MapTypes, - HYBRID: MapTypes, - TERRAIN: MapTypes, - NONE: MapTypes, - MUTEDSTANDARD: MapTypes, + export interface MapCalloutProps { + tooltip?: boolean; + onPress?: Function; + style?: any; } - export const PROVIDER_DEFAULT: null; - export const PROVIDER_GOOGLE: 'google'; - + export class Marker extends React.Component { + showCallout(): void; + hideCallout(): void; + animateMarkerToCoordinate(coordinate: LatLng, duration: number): void; + } + export class Polyline extends React.Component { } + export class Polygon extends React.Component { } + export class Circle extends React.Component { } + export class UrlTile extends React.Component { } + export class LocalTile extends React.Component { } + export class MbTile extends React.Component { } + export class Callout extends React.Component { } } diff --git a/index.js b/index.js old mode 100644 new mode 100755 index acc1f7553..841cd16cd --- a/index.js +++ b/index.js @@ -1,23 +1,17 @@ -import MapView, { Animated, MAP_TYPES, ProviderPropType } from './lib/components/MapView'; -import Marker from './lib/components/MapMarker.js'; -import Overlay from './lib/components/MapOverlay.js'; +import MapView from './lib/components/MapView'; +export { default as Marker } from './lib/components/MapMarker.js'; export { default as Polyline } from './lib/components/MapPolyline.js'; export { default as Polygon } from './lib/components/MapPolygon.js'; export { default as Circle } from './lib/components/MapCircle.js'; export { default as UrlTile } from './lib/components/MapUrlTile.js'; export { default as LocalTile } from './lib/components/MapLocalTile.js'; +export { default as MbTile } from './lib/components/MapMbTile.js'; +export { default as Overlay } from './lib/components/MapOverlay.js'; export { default as Callout } from './lib/components/MapCallout.js'; export { default as AnimatedRegion } from './lib/components/AnimatedRegion.js'; - -export { Marker, Overlay }; -export { Animated, MAP_TYPES, ProviderPropType }; - +export { Animated, ProviderPropType, MAP_TYPES } from './lib/components/MapView.js'; export const PROVIDER_GOOGLE = MapView.PROVIDER_GOOGLE; export const PROVIDER_DEFAULT = MapView.PROVIDER_DEFAULT; -export const MarkerAnimated = Marker.Animated; -export const OverlayAnimated = Overlay.Animated; - export default MapView; - diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java new file mode 100644 index 000000000..7fd861e52 --- /dev/null +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -0,0 +1,139 @@ +package com.airbnb.android.react.maps; + +import android.content.Context; + +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.model.Tile; +import com.google.android.gms.maps.model.TileOverlay; +import com.google.android.gms.maps.model.TileOverlayOptions; +import com.google.android.gms.maps.model.TileProvider; + +import java.io.File; + +import android.os.Environment; +import android.database.sqlite.SQLiteDatabase; +import android.database.Cursor; + +/** + * Created by Christoph Lambio on 30/03/2018. + * Based on AirMapLocalTileManager.java + * Copyright (c) zavadpe + */ + +public class AirMapMbTile extends AirMapFeature { + + class AIRMapMbTileProvider implements TileProvider { + private static final int BUFFER_SIZE = 16 * 1024; + private int tileSize; + private String pathTemplate; + + + public AIRMapMbTileProvider(int tileSizet, String pathTemplate) { + this.tileSize = tileSizet; + this.pathTemplate = pathTemplate; + } + + @Override + public Tile getTile(int x, int y, int zoom) { + byte[] image = readTileImage(x, y, zoom); + return image == null ? TileProvider.NO_TILE : new Tile(this.tileSize, this.tileSize, image); + } + + public void setPathTemplate(String pathTemplate) { + this.pathTemplate = pathTemplate; + } + + public void setTileSize(int tileSize) { + this.tileSize = tileSize; + } + + private byte[] readTileImage(int x, int y, int zoom) { + String rawQuery = "SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y}"; + + try { + SQLiteDatabase offlineDataDatabase = SQLiteDatabase.openDatabase(this.pathTemplate, null, SQLiteDatabase.OPEN_READONLY); + String query = rawQuery.replace("{x}", Integer.toString(x)) + .replace("{y}", Integer.toString(y)) + .replace("{z}", Integer.toString(zoom)); + Cursor cursor = offlineDataDatabase.rawQuery(query, null); + if(cursor.moveToFirst()){ + byte[] tile = cursor.getBlob(5); + cursor.close(); + offlineDataDatabase.close(); + return tile; + } + offlineDataDatabase.close(); + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + } + + private TileOverlayOptions tileOverlayOptions; + private TileOverlay tileOverlay; + private AirMapMbTile.AIRMapMbTileProvider tileProvider; + + private String pathTemplate; + private float tileSize; + private float zIndex; + + public AirMapMbTile(Context context) { + super(context); + } + + public void setPathTemplate(String pathTemplate) { + this.pathTemplate = pathTemplate; + if (tileProvider != null) { + tileProvider.setPathTemplate(pathTemplate); + } + if (tileOverlay != null) { + tileOverlay.clearTileCache(); + } + } + + public void setZIndex(float zIndex) { + this.zIndex = zIndex; + if (tileOverlay != null) { + tileOverlay.setZIndex(zIndex); + } + } + + public void setTileSize(float tileSize) { + this.tileSize = tileSize; + if (tileProvider != null) { + tileProvider.setTileSize((int)tileSize); + } + } + + public TileOverlayOptions getTileOverlayOptions() { + if (tileOverlayOptions == null) { + tileOverlayOptions = createTileOverlayOptions(); + } + return tileOverlayOptions; + } + + private TileOverlayOptions createTileOverlayOptions() { + TileOverlayOptions options = new TileOverlayOptions(); + options.zIndex(zIndex); + this.tileProvider = new AirMapMbTile.AIRMapMbTileProvider((int)this.tileSize, this.pathTemplate); + options.tileProvider(this.tileProvider); + return options; + } + + @Override + public Object getFeature() { + return tileOverlay; + } + + @Override + public void addToMap(GoogleMap map) { + this.tileOverlay = map.addTileOverlay(getTileOverlayOptions()); + } + + @Override + public void removeFromMap(GoogleMap map) { + tileOverlay.remove(); + } +} diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTileManager.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTileManager.java new file mode 100644 index 000000000..cb3e2e549 --- /dev/null +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTileManager.java @@ -0,0 +1,56 @@ +package com.airbnb.android.react.maps; + +import android.content.Context; +import android.os.Build; +import android.util.DisplayMetrics; +import android.view.WindowManager; + +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.react.uimanager.ViewGroupManager; +import com.facebook.react.uimanager.annotations.ReactProp; + +/** + * Created by Christoph Lambio on 30/03/2018. + * Based on AirMapLocalTileManager.java + * Copyright (c) zavadpe + */ +public class AirMapMbTileManager extends ViewGroupManager { + private DisplayMetrics metrics; + + public AirMapMbTileManager(ReactApplicationContext reactContext) { + super(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + metrics = new DisplayMetrics(); + ((WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay() + .getRealMetrics(metrics); + } else { + metrics = reactContext.getResources().getDisplayMetrics(); + } + } + + @Override + public String getName() { + return "AIRMapMbTile"; + } + + @Override + public AirMapMbTile createViewInstance(ThemedReactContext context) { + return new AirMapMbTile(context); + } + + @ReactProp(name = "pathTemplate") + public void setPathTemplate(AirMapMbTile view, String pathTemplate) { view.setPathTemplate(pathTemplate); } + + @ReactProp(name = "tileSize", defaultFloat = 256f) + public void setTileSize(AirMapMbTile view, float tileSize) { + view.setTileSize(tileSize); + } + + @ReactProp(name = "zIndex", defaultFloat = -1.0f) + public void setZIndex(AirMapMbTile view, float zIndex) { + view.setZIndex(zIndex); + } + +} \ No newline at end of file diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java old mode 100644 new mode 100755 index f270374c8..a41794d34 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java @@ -8,6 +8,7 @@ import android.graphics.Point; import android.graphics.PorterDuff; import android.os.Build; +import android.os.Handler; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.view.MotionEventCompat; import android.view.GestureDetector; @@ -17,15 +18,12 @@ import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; -import android.location.Location; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; -import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; @@ -37,37 +35,25 @@ import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.Projection; -import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; -import com.google.android.gms.maps.model.MarkerOptions; -import com.google.android.gms.maps.model.PointOfInterest; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.Polyline; -import com.google.maps.android.data.kml.KmlContainer; -import com.google.maps.android.data.kml.KmlLayer; -import com.google.maps.android.data.kml.KmlPlacemark; -import com.google.maps.android.data.kml.KmlStyle; +import com.google.android.gms.maps.model.VisibleRegion; -import org.xmlpull.v1.XmlPullParserException; - -import java.io.IOException; -import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.ExecutionException; import static android.support.v4.content.PermissionChecker.checkSelfPermission; public class AirMapView extends MapView implements GoogleMap.InfoWindowAdapter, - GoogleMap.OnMarkerDragListener, OnMapReadyCallback, GoogleMap.OnPoiClickListener { + GoogleMap.OnMarkerDragListener, OnMapReadyCallback { public GoogleMap map; - private KmlLayer kmlLayer; private ProgressBar mapLoadingProgressBar; private RelativeLayout mapLoadingLayout; private ImageView cacheImageView; @@ -179,38 +165,16 @@ public void onMapReady(final GoogleMap map) { this.map = map; this.map.setInfoWindowAdapter(this); this.map.setOnMarkerDragListener(this); - this.map.setOnPoiClickListener(this); manager.pushEvent(context, this, "onMapReady", new WritableNativeMap()); final AirMapView view = this; - map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { - @Override - public void onMyLocationChange(Location location){ - WritableMap event = new WritableNativeMap(); - - WritableMap coordinate = new WritableNativeMap(); - coordinate.putDouble("latitude", location.getLatitude()); - coordinate.putDouble("longitude", location.getLongitude()); - coordinate.putDouble("altitude", location.getAltitude()); - coordinate.putDouble("accuracy", location.getAccuracy()); - coordinate.putDouble("speed", location.getSpeed()); - if(android.os.Build.VERSION.SDK_INT >= 18){ - coordinate.putBoolean("isFromMockProvider", location.isFromMockProvider()); - } - - event.putMap("coordinate", coordinate); - - manager.pushEvent(context, view, "onUserLocationChange", event); - } - }); - map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { WritableMap event; - AirMapMarker airMapMarker = getMarkerMap(marker); + AirMapMarker airMapMarker = markerMap.get(marker); event = makeClickEventData(marker.getPosition()); event.putString("action", "marker-press"); @@ -220,7 +184,7 @@ public boolean onMarkerClick(Marker marker) { event = makeClickEventData(marker.getPosition()); event.putString("action", "marker-press"); event.putString("id", airMapMarker.getIdentifier()); - manager.pushEvent(context, airMapMarker, "onPress", event); + manager.pushEvent(context, markerMap.get(marker), "onPress", event); // Return false to open the callout info window and center on the marker // https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap @@ -263,7 +227,7 @@ public void onInfoWindowClick(Marker marker) { event = makeClickEventData(marker.getPosition()); event.putString("action", "callout-press"); - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); manager.pushEvent(context, markerView, "onCalloutPress", event); event = makeClickEventData(marker.getPosition()); @@ -542,6 +506,10 @@ public void addFeature(View child, int index) { AirMapLocalTile localTileView = (AirMapLocalTile) child; localTileView.addToMap(map); features.add(index, localTileView); + } else if (child instanceof AirMapMbTile) { + AirMapMbTile mbTileView = (AirMapMbTile) child; + mbTileView.addToMap(map); + features.add(index, mbTileView); } else if (child instanceof AirMapOverlay) { AirMapOverlay overlayView = (AirMapOverlay) child; overlayView.addToMap(map); @@ -752,13 +720,13 @@ public void setMapBoundaries(ReadableMap northEast, ReadableMap southWest) { @Override public View getInfoWindow(Marker marker) { - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); return markerView.getCallout(); } @Override public View getInfoContents(Marker marker) { - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); return markerView.getInfoContents(); } @@ -787,7 +755,7 @@ public void onMarkerDragStart(Marker marker) { WritableMap event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, this, "onMarkerDragStart", event); - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, markerView, "onDragStart", event); } @@ -797,7 +765,7 @@ public void onMarkerDrag(Marker marker) { WritableMap event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, this, "onMarkerDrag", event); - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, markerView, "onDrag", event); } @@ -807,21 +775,11 @@ public void onMarkerDragEnd(Marker marker) { WritableMap event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, this, "onMarkerDragEnd", event); - AirMapMarker markerView = getMarkerMap(marker); + AirMapMarker markerView = markerMap.get(marker); event = makeClickEventData(marker.getPosition()); manager.pushEvent(context, markerView, "onDragEnd", event); } - @Override - public void onPoiClick(PointOfInterest poi) { - WritableMap event = makeClickEventData(poi.latLng); - - event.putString("placeId", poi.placeId); - event.putString("name", poi.name); - - manager.pushEvent(context, this, "onPoiClick", event); - } - private ProgressBar getMapLoadingProgressBar() { if (this.mapLoadingProgressBar == null) { this.mapLoadingProgressBar = new ProgressBar(getContext()); @@ -914,118 +872,4 @@ public void onPanDrag(MotionEvent ev) { WritableMap event = makeClickEventData(coords); manager.pushEvent(context, this, "onPanDrag", event); } - - public void setKmlSrc(String kmlSrc) { - try { - InputStream kmlStream = new FileUtil(context).execute(kmlSrc).get(); - - if (kmlStream == null) { - return; - } - - kmlLayer = new KmlLayer(map, kmlStream, context); - kmlLayer.addLayerToMap(); - - WritableMap pointers = new WritableNativeMap(); - WritableArray markers = new WritableNativeArray(); - - if (kmlLayer.getContainers() == null) { - manager.pushEvent(context, this, "onKmlReady", pointers); - return; - } - - //Retrieve a nested container within the first container - KmlContainer container = kmlLayer.getContainers().iterator().next(); - if (container == null || container.getContainers() == null) { - manager.pushEvent(context, this, "onKmlReady", pointers); - return; - } - - - if (container.getContainers().iterator().hasNext()) { - container = container.getContainers().iterator().next(); - } - - Integer index = 0; - for (KmlPlacemark placemark : container.getPlacemarks()) { - MarkerOptions options = new MarkerOptions(); - - if (placemark.getInlineStyle() != null) { - options = placemark.getMarkerOptions(); - } else { - options.icon(BitmapDescriptorFactory.defaultMarker()); - } - - LatLng latLng = ((LatLng) placemark.getGeometry().getGeometryObject()); - String title = ""; - String snippet = ""; - - if (placemark.hasProperty("name")) { - title = placemark.getProperty("name"); - } - - if (placemark.hasProperty("description")) { - snippet = placemark.getProperty("description"); - } - - options.position(latLng); - options.title(title); - options.snippet(snippet); - - AirMapMarker marker = new AirMapMarker(context, options); - - if (placemark.getInlineStyle() != null - && placemark.getInlineStyle().getIconUrl() != null) { - marker.setImage(placemark.getInlineStyle().getIconUrl()); - } else if (container.getStyle(placemark.getStyleId()) != null) { - KmlStyle style = container.getStyle(placemark.getStyleId()); - marker.setImage(style.getIconUrl()); - } - - String identifier = title + " - " + index; - - marker.setIdentifier(identifier); - - addFeature(marker, index++); - - WritableMap loadedMarker = makeClickEventData(latLng); - loadedMarker.putString("id", identifier); - loadedMarker.putString("title", title); - loadedMarker.putString("description", snippet); - - markers.pushMap(loadedMarker); - } - - pointers.putArray("markers", markers); - - manager.pushEvent(context, this, "onKmlReady", pointers); - - } catch (XmlPullParserException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - - private AirMapMarker getMarkerMap(Marker marker) { - AirMapMarker airMarker = markerMap.get(marker); - - if (airMarker != null) { - return airMarker; - } - - for (Map.Entry entryMarker : markerMap.entrySet()) { - if (entryMarker.getKey().getPosition().equals(marker.getPosition()) - && entryMarker.getKey().getTitle().equals(marker.getTitle())) { - airMarker = entryMarker.getValue(); - break; - } - } - - return airMarker; - } } diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/MapsPackage.java b/lib/android/src/main/java/com/airbnb/android/react/maps/MapsPackage.java old mode 100644 new mode 100755 index 45364b3be..e1d385021 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/MapsPackage.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/MapsPackage.java @@ -40,6 +40,7 @@ public List createViewManagers(ReactApplicationContext reactContext AirMapLiteManager mapLiteManager = new AirMapLiteManager(reactContext); AirMapUrlTileManager urlTileManager = new AirMapUrlTileManager(reactContext); AirMapLocalTileManager localTileManager = new AirMapLocalTileManager(reactContext); + AirMapMbTileManager mbTileManager = new AirMapMbTileManager(reactContext); AirMapOverlayManager overlayManager = new AirMapOverlayManager(reactContext); return Arrays.asList( @@ -52,6 +53,7 @@ public List createViewManagers(ReactApplicationContext reactContext mapLiteManager, urlTileManager, localTileManager, + mbTileManager, overlayManager ); } diff --git a/lib/components/MapMbTile.js b/lib/components/MapMbTile.js new file mode 100644 index 000000000..d439d2781 --- /dev/null +++ b/lib/components/MapMbTile.js @@ -0,0 +1,71 @@ +// +// MapMbTile.js +// AirMaps +// +// Created by Christoph Lambio on 27/03/2018. +// Based on AIRMapLocalTileManager.h +// + +import PropTypes from 'prop-types'; +import React from 'react'; + +import { + ViewPropTypes, + View, +} from 'react-native'; + +import decorateMapComponent, { + USES_DEFAULT_IMPLEMENTATION, + SUPPORTED, +} from './decorateMapComponent'; + +// if ViewPropTypes is not defined fall back to View.propType (to support RN < 0.44) +const viewPropTypes = ViewPropTypes || View.propTypes; + +const propTypes = { + ...viewPropTypes, + + /** + * The path template of the MBTiles database tile source. + * The patterns {x} {y} {z} will be replaced at runtime, + * for example, /storage/emulated/0/tiles/{z}/{x}/{y}.png. + */ + pathTemplate: PropTypes.string.isRequired, + + /** + * The order in which this tile overlay is drawn with respect to other overlays. An overlay + * with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays + * with the same z-index is arbitrary. The default zIndex is -1. + * + * @platform android + */ + zIndex: PropTypes.number, + + /** + * Size of tile images. + */ + tileSize: PropTypes.number, +}; + +class MapMbTile extends React.Component { + render() { + const AIRMapMbTile = this.getAirComponent(); + return ( + + ); + } +} + +MapMbTile.propTypes = propTypes; + +export default decorateMapComponent(MapMbTile, { + componentType: 'MbTile', + providers: { + google: { + ios: SUPPORTED, + android: USES_DEFAULT_IMPLEMENTATION, + }, + }, +}); diff --git a/lib/components/MapView.js b/lib/components/MapView.js old mode 100644 new mode 100755 index f8011f148..c18046b18 --- a/lib/components/MapView.js +++ b/lib/components/MapView.js @@ -19,6 +19,7 @@ import MapCallout from './MapCallout'; import MapOverlay from './MapOverlay'; import MapUrlTile from './MapUrlTile'; import MapLocalTile from './MapLocalTile'; +import MapMbTile from './MapMbTile'; import AnimatedRegion from './AnimatedRegion'; import { contextTypes as childContextTypes, @@ -347,11 +348,6 @@ const propTypes = { */ onMapReady: PropTypes.func, - /** - * Callback that is called once the kml is fully loaded. - */ - onKmlReady: PropTypes.func, - /** * Callback that is called continuously when the user is dragging the map. */ @@ -372,21 +368,11 @@ const propTypes = { */ onLongPress: PropTypes.func, - /** - * Callback that is called when the underlying map figures our users current location. - */ - onUserLocationChange: PropTypes.func, - /** * Callback that is called when user makes a "drag" somewhere on the map */ onPanDrag: PropTypes.func, - /** - * Callback that is called when user click on a POI - */ - onPoiClick: PropTypes.func, - /** * Callback that is called when a marker on the map is tapped by the user. */ @@ -439,11 +425,6 @@ const propTypes = { */ maxZoomLevel: PropTypes.number, - /** - * Url KML Source - */ - kmlSrc: PropTypes.string, - }; class MapView extends React.Component { @@ -663,7 +644,18 @@ class MapView extends React.Component { if (Platform.OS === 'android') { return NativeModules.AirMapModule.pointForCoordinate(this._getHandle(), coordinate); } else if (Platform.OS === 'ios') { - return this._runCommand('pointForCoordinate', [coordinate]); + return new Promise((resolve, reject) => { + this._runCommand('pointForCoordinate', [ + coordinate, + (err, snapshot) => { + if (err) { + reject(err); + } else { + resolve(snapshot); + } + }, + ]); + }); } return Promise.reject('pointForCoordinate not supported on this platform'); } @@ -677,13 +669,24 @@ class MapView extends React.Component { * * @return Promise Promise with the coordinate ({ latitude: Number, longitude: Number }) */ - coordinateForPoint(point) { + coordinateFromPoint(point) { if (Platform.OS === 'android') { - return NativeModules.AirMapModule.coordinateForPoint(this._getHandle(), point); + return NativeModules.AirMapModule.coordinateFromPoint(this._getHandle(), point); } else if (Platform.OS === 'ios') { - return this._runCommand('coordinateForPoint', [point]); + return new Promise((resolve, reject) => { + this._runCommand('coordinateFromPoint', [ + point, + (err, snapshot) => { + if (err) { + reject(err); + } else { + resolve(snapshot); + } + }, + ]); + }); } - return Promise.reject('coordinateForPoint not supported on this platform'); + return Promise.reject('coordinateFromPoint not supported on this platform'); } _uiManagerCommand(name) { @@ -701,17 +704,19 @@ class MapView extends React.Component { _runCommand(name, args) { switch (Platform.OS) { case 'android': - return NativeModules.UIManager.dispatchViewManagerCommand( + NativeModules.UIManager.dispatchViewManagerCommand( this._getHandle(), this._uiManagerCommand(name), args ); + break; case 'ios': - return this._mapManagerCommand(name)(this._getHandle(), ...args); + this._mapManagerCommand(name)(this._getHandle(), ...args); + break; default: - return Promise.reject(`Invalid platform was passed: ${Platform.OS}`); + break; } } @@ -775,7 +780,6 @@ const nativeComponent = Component => requireNativeComponent(Component, MapView, nativeOnly: { onChange: true, onMapReady: true, - onKmlReady: true, handlePanDrag: true, }, }); @@ -817,6 +821,7 @@ MapView.Polygon = MapPolygon; MapView.Circle = MapCircle; MapView.UrlTile = MapUrlTile; MapView.LocalTile = MapLocalTile; +MapView.MbTile = MapMbTile; MapView.Overlay = MapOverlay; MapView.Callout = MapCallout; Object.assign(MapView, ProviderConstants); diff --git a/lib/ios/AirMaps.xcodeproj/project.pbxproj b/lib/ios/AirMaps.xcodeproj/project.pbxproj index 4bb684b04..270bc56eb 100644 --- a/lib/ios/AirMaps.xcodeproj/project.pbxproj +++ b/lib/ios/AirMaps.xcodeproj/project.pbxproj @@ -48,6 +48,9 @@ 9B9498DA2017EFB800158761 /* AIRGoogleMapPolygon.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B9498C62017EFB800158761 /* AIRGoogleMapPolygon.m */; }; 9B9498DB2017EFB800158761 /* AIRGoogleMapMarker.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B9498C72017EFB800158761 /* AIRGoogleMapMarker.m */; }; 9B9498DC2017EFB800158761 /* AIRGoogleMapPolygonManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B9498C92017EFB800158761 /* AIRGoogleMapPolygonManager.m */; }; + BD9BE2902087408600A3E492 /* AIRMapMbTile.m in Sources */ = {isa = PBXBuildFile; fileRef = BD9BE28C2087408500A3E492 /* AIRMapMbTile.m */; }; + BD9BE2912087408600A3E492 /* AIRMapMbTileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = BD9BE28D2087408600A3E492 /* AIRMapMbTileManager.m */; }; + BD9BE2922087408600A3E492 /* AIRMapMbTileOverlay.m in Sources */ = {isa = PBXBuildFile; fileRef = BD9BE28F2087408600A3E492 /* AIRMapMbTileOverlay.m */; }; DA6C26381C9E2AFE0035349F /* AIRMapUrlTile.m in Sources */ = {isa = PBXBuildFile; fileRef = DA6C26371C9E2AFE0035349F /* AIRMapUrlTile.m */; }; DA6C263E1C9E324A0035349F /* AIRMapUrlTileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = DA6C263D1C9E324A0035349F /* AIRMapUrlTileManager.m */; }; /* End PBXBuildFile section */ @@ -147,6 +150,23 @@ 9B9498C72017EFB800158761 /* AIRGoogleMapMarker.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AIRGoogleMapMarker.m; path = AirGoogleMaps/AIRGoogleMapMarker.m; sourceTree = ""; }; 9B9498C82017EFB800158761 /* AIRGoogleMapUrlTile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AIRGoogleMapUrlTile.h; path = AirGoogleMaps/AIRGoogleMapUrlTile.h; sourceTree = ""; }; 9B9498C92017EFB800158761 /* AIRGoogleMapPolygonManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AIRGoogleMapPolygonManager.m; path = AirGoogleMaps/AIRGoogleMapPolygonManager.m; sourceTree = ""; }; + BD9BE28A2087408500A3E492 /* AIRMapMbTileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AIRMapMbTileManager.h; sourceTree = ""; }; + BD9BE28B2087408500A3E492 /* AIRMapMbTile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AIRMapMbTile.h; sourceTree = ""; }; + BD9BE28C2087408500A3E492 /* AIRMapMbTile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AIRMapMbTile.m; sourceTree = ""; }; + BD9BE28D2087408600A3E492 /* AIRMapMbTileManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AIRMapMbTileManager.m; sourceTree = ""; }; + BD9BE28E2087408600A3E492 /* AIRMapMbTileOverlay.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AIRMapMbTileOverlay.h; sourceTree = ""; }; + BD9BE28F2087408600A3E492 /* AIRMapMbTileOverlay.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AIRMapMbTileOverlay.m; sourceTree = ""; }; + BD9BE2942087408F00A3E492 /* FMDatabase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; + BD9BE2952087408F00A3E492 /* FMDatabase.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = ""; }; + BD9BE2962087408F00A3E492 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = ""; }; + BD9BE2972087408F00A3E492 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = ""; }; + BD9BE2982087408F00A3E492 /* FMDatabasePool.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = ""; }; + BD9BE2992087408F00A3E492 /* FMDatabasePool.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = ""; }; + BD9BE29A2087408F00A3E492 /* FMDatabaseQueue.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = ""; }; + BD9BE29B2087408F00A3E492 /* FMDatabaseQueue.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = ""; }; + BD9BE29C2087408F00A3E492 /* FMDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = ""; }; + BD9BE29D2087408F00A3E492 /* FMResultSet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = ""; }; + BD9BE29E2087408F00A3E492 /* FMResultSet.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = ""; }; DA6C26361C9E2AFE0035349F /* AIRMapUrlTile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AIRMapUrlTile.h; sourceTree = ""; }; DA6C26371C9E2AFE0035349F /* AIRMapUrlTile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AIRMapUrlTile.m; sourceTree = ""; }; DA6C263C1C9E324A0035349F /* AIRMapUrlTileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AIRMapUrlTileManager.h; sourceTree = ""; }; @@ -167,6 +187,7 @@ 11FA5C481C4A1296003AC2EE = { isa = PBXGroup; children = ( + BD9BE2932087408F00A3E492 /* fmdb */, 9B9498A32017EF9D00158761 /* AirGoogleMaps */, 62AEC4D31FD5A0AA003225E0 /* AIRMapLocalTileOverlay.m */, 11FA5C531C4A1296003AC2EE /* AirMaps */, @@ -185,6 +206,12 @@ 11FA5C531C4A1296003AC2EE /* AirMaps */ = { isa = PBXGroup; children = ( + BD9BE28B2087408500A3E492 /* AIRMapMbTile.h */, + BD9BE28C2087408500A3E492 /* AIRMapMbTile.m */, + BD9BE28A2087408500A3E492 /* AIRMapMbTileManager.h */, + BD9BE28D2087408600A3E492 /* AIRMapMbTileManager.m */, + BD9BE28E2087408600A3E492 /* AIRMapMbTileOverlay.h */, + BD9BE28F2087408600A3E492 /* AIRMapMbTileOverlay.m */, 1125B2BD1C4AD3DA007D0023 /* AIRMap.h */, 1125B2BE1C4AD3DA007D0023 /* AIRMap.m */, 1125B2BF1C4AD3DA007D0023 /* AIRMapCallout.h */, @@ -280,6 +307,25 @@ name = AirGoogleMaps; sourceTree = ""; }; + BD9BE2932087408F00A3E492 /* fmdb */ = { + isa = PBXGroup; + children = ( + BD9BE2942087408F00A3E492 /* FMDatabase.h */, + BD9BE2952087408F00A3E492 /* FMDatabase.m */, + BD9BE2962087408F00A3E492 /* FMDatabaseAdditions.h */, + BD9BE2972087408F00A3E492 /* FMDatabaseAdditions.m */, + BD9BE2982087408F00A3E492 /* FMDatabasePool.h */, + BD9BE2992087408F00A3E492 /* FMDatabasePool.m */, + BD9BE29A2087408F00A3E492 /* FMDatabaseQueue.h */, + BD9BE29B2087408F00A3E492 /* FMDatabaseQueue.m */, + BD9BE29C2087408F00A3E492 /* FMDB.h */, + BD9BE29D2087408F00A3E492 /* FMResultSet.h */, + BD9BE29E2087408F00A3E492 /* FMResultSet.m */, + ); + name = fmdb; + path = AirMaps/fmdb; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -339,6 +385,7 @@ 62AEC4D41FD5A0AA003225E0 /* AIRMapLocalTileOverlay.m in Sources */, 9B9498DC2017EFB800158761 /* AIRGoogleMapPolygonManager.m in Sources */, 1125B2E31C4AD3DA007D0023 /* AIRMapPolygon.m in Sources */, + BD9BE2922087408600A3E492 /* AIRMapMbTileOverlay.m in Sources */, 1125B2E41C4AD3DA007D0023 /* AIRMapPolygonManager.m in Sources */, 9B9498CB2017EFB800158761 /* AIRGoogleMapURLTileManager.m in Sources */, 1125B2DB1C4AD3DA007D0023 /* AIRMapCallout.m in Sources */, @@ -352,6 +399,7 @@ 9B9498D72017EFB800158761 /* AIRGoogleMapManager.m in Sources */, 19DABC7F1E7C9D3C00F41150 /* RCTConvert+AirMap.m in Sources */, 1125B2E51C4AD3DA007D0023 /* AIRMapPolyline.m in Sources */, + BD9BE2902087408600A3E492 /* AIRMapMbTile.m in Sources */, 9B9498D82017EFB800158761 /* DummyView.m in Sources */, 9B9498D52017EFB800158761 /* AIRGoogleMapPolyline.m in Sources */, 9B9498CF2017EFB800158761 /* AIRGMSPolyline.m in Sources */, @@ -367,6 +415,7 @@ 1125B2DF1C4AD3DA007D0023 /* AIRMapCoordinate.m in Sources */, 9B9498D62017EFB800158761 /* AIRGoogleMapCircleManager.m in Sources */, 1125B2F21C4AD445007D0023 /* SMCalloutView.m in Sources */, + BD9BE2912087408600A3E492 /* AIRMapMbTileManager.m in Sources */, 2163AA501FEAEDD100BBEC95 /* AIRMapPolylineRenderer.m in Sources */, 9B9498D02017EFB800158761 /* AIRGoogleMapPolylineManager.m in Sources */, 1125B2E11C4AD3DA007D0023 /* AIRMapMarker.m in Sources */, diff --git a/lib/ios/AirMaps/AIRMap.m b/lib/ios/AirMaps/AIRMap.m old mode 100644 new mode 100755 index 959dede7c..70cc14c4b --- a/lib/ios/AirMaps/AIRMap.m +++ b/lib/ios/AirMaps/AIRMap.m @@ -18,7 +18,7 @@ #import #import "AIRMapUrlTile.h" #import "AIRMapLocalTile.h" -#import "AIRMapOverlay.h" +#import "AIRMapMbTile.h" const CLLocationDegrees AIRMapDefaultSpan = 0.005; const NSTimeInterval AIRMapRegionChangeObserveInterval = 0.1; @@ -116,7 +116,6 @@ - (void)insertReactSubview:(id)subview atIndex:(NSInteger)atIndex ((AIRMapPolygon *)subview).map = self; [self addOverlay:(id)subview]; } else if ([subview isKindOfClass:[AIRMapCircle class]]) { - ((AIRMapCircle *)subview).map = self; [self addOverlay:(id)subview]; } else if ([subview isKindOfClass:[AIRMapUrlTile class]]) { ((AIRMapUrlTile *)subview).map = self; @@ -124,8 +123,8 @@ - (void)insertReactSubview:(id)subview atIndex:(NSInteger)atIndex } else if ([subview isKindOfClass:[AIRMapLocalTile class]]) { ((AIRMapLocalTile *)subview).map = self; [self addOverlay:(id)subview]; - } else if ([subview isKindOfClass:[AIRMapOverlay class]]) { - ((AIRMapOverlay *)subview).map = self; + } else if ([subview isKindOfClass:[AIRMapMbTile class]]) { + ((AIRMapMbTile *)subview).map = self; [self addOverlay:(id)subview]; } else { NSArray> *childSubviews = [subview reactSubviews]; @@ -154,7 +153,7 @@ - (void)removeReactSubview:(id)subview { [self removeOverlay:(id ) subview]; } else if ([subview isKindOfClass:[AIRMapLocalTile class]]) { [self removeOverlay:(id ) subview]; - } else if ([subview isKindOfClass:[AIRMapOverlay class]]) { + } else if ([subview isKindOfClass:[AIRMapMbTile class]]) { [self removeOverlay:(id ) subview]; } else { NSArray> *childSubviews = [subview reactSubviews]; @@ -317,6 +316,38 @@ - (void)setLoadingIndicatorColor:(UIColor *)loadingIndicatorColor { self.activityIndicatorView.color = loadingIndicatorColor; } +RCT_EXPORT_METHOD(pointForCoordinate:(NSDictionary *)coordinate resolver: (RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) +{ + CGPoint touchPoint = [self convertCoordinate: + CLLocationCoordinate2DMake( + [coordinate[@"lat"] doubleValue], + [coordinate[@"lng"] doubleValue] + ) + toPointToView:self]; + + resolve(@{ + @"x": @(touchPoint.x), + @"y": @(touchPoint.y), + }); +} + +RCT_EXPORT_METHOD(coordinateForPoint:(NSDictionary *)point resolver: (RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) +{ + CLLocationCoordinate2D coordinate = [self convertPoint: + CGPointMake( + [point[@"x"] doubleValue], + [point[@"y"] doubleValue] + ) + toCoordinateFromView:self]; + + resolve(@{ + @"lat": @(coordinate.latitude), + @"lng": @(coordinate.longitude), + }); +} + // Include properties of MKMapView which are only available on iOS 9+ // and check if their selector is available before calling super method. diff --git a/lib/ios/AirMaps/AIRMapManager.m b/lib/ios/AirMaps/AIRMapManager.m old mode 100644 new mode 100755 index a14dc320e..c5947c23e --- a/lib/ios/AirMaps/AIRMapManager.m +++ b/lib/ios/AirMaps/AIRMapManager.m @@ -24,9 +24,9 @@ #import "SMCalloutView.h" #import "AIRMapUrlTile.h" #import "AIRMapLocalTile.h" +#import "AIRMapMbTile.h" #import "AIRMapSnapshot.h" #import "RCTConvert+AirMap.h" -#import "AIRMapOverlay.h" #import @@ -75,7 +75,6 @@ - (UIView *)view RCT_EXPORT_VIEW_PROPERTY(showsScale, BOOL) RCT_EXPORT_VIEW_PROPERTY(showsTraffic, BOOL) RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL) -RCT_EXPORT_VIEW_PROPERTY(kmlSrc, NSString) RCT_EXPORT_VIEW_PROPERTY(rotateEnabled, BOOL) RCT_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) RCT_EXPORT_VIEW_PROPERTY(pitchEnabled, BOOL) @@ -317,58 +316,6 @@ - (UIView *)view }]; } -RCT_EXPORT_METHOD(pointForCoordinate:(nonnull NSNumber *)reactTag - coordinate: (NSDictionary *)coordinate - resolver: (RCTPromiseResolveBlock)resolve - rejecter:(RCTPromiseRejectBlock)reject) -{ - [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { - id view = viewRegistry[reactTag]; - AIRMap *mapView = (AIRMap *)view; - if (![view isKindOfClass:[AIRMap class]]) { - reject(@"Invalid argument", [NSString stringWithFormat:@"Invalid view returned from registry, expecting AIRMap, got: %@", view], NULL); - } else { - CGPoint touchPoint = [mapView convertCoordinate: - CLLocationCoordinate2DMake( - [coordinate[@"lat"] doubleValue], - [coordinate[@"lng"] doubleValue] - ) - toPointToView:mapView]; - - resolve(@{ - @"x": @(touchPoint.x), - @"y": @(touchPoint.y), - }); - } - }]; -} - -RCT_EXPORT_METHOD(coordinateForPoint:(nonnull NSNumber *)reactTag - point:(NSDictionary *)point - resolver: (RCTPromiseResolveBlock)resolve - rejecter:(RCTPromiseRejectBlock)reject) -{ - [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { - id view = viewRegistry[reactTag]; - AIRMap *mapView = (AIRMap *)view; - if (![view isKindOfClass:[AIRMap class]]) { - reject(@"Invalid argument", [NSString stringWithFormat:@"Invalid view returned from registry, expecting AIRMap, got: %@", view], NULL); - } else { - CLLocationCoordinate2D coordinate = [mapView convertPoint: - CGPointMake( - [point[@"x"] doubleValue], - [point[@"y"] doubleValue] - ) - toCoordinateFromView:mapView]; - - resolve(@{ - @"lat": @(coordinate.latitude), - @"lng": @(coordinate.longitude), - }); - } - }]; -} - #pragma mark Take Snapshot - (void)takeMapSnapshot:(AIRMap *)mapView snapshotter:(MKMapSnapshotter *) snapshotter @@ -510,24 +457,6 @@ - (void)handleMapTap:(UITapGestureRecognizer *)recognizer { } } } - - if ([overlay isKindOfClass:[AIRMapOverlay class]]) { - AIRMapOverlay *imageOverlay = (AIRMapOverlay*) overlay; - if (MKMapRectContainsPoint(imageOverlay.boundingMapRect, mapPoint)) { - if (imageOverlay.onPress) { - id event = @{ - @"action": @"image-overlay-press", - @"name": imageOverlay.name ?: @"unknown", - @"coordinate": @{ - @"latitude": @(imageOverlay.coordinate.latitude), - @"longitude": @(imageOverlay.coordinate.longitude) - } - }; - imageOverlay.onPress(event); - } - } - } - } if (nearestDistance <= maxMeters) { @@ -609,8 +538,8 @@ - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id +#import +#import + +#import +#import +#import "AIRMapCoordinate.h" +#import "AIRMap.h" +#import "RCTConvert+AirMap.h" + +#import +#import +#import + +#import +#import +#import "AIRMapCoordinate.h" +#import "AIRMap.h" +#import "RCTConvert+AirMap.h" + +@interface AIRMapMbTile : MKAnnotationView + +@property (nonatomic, weak) AIRMap *map; + +@property (nonatomic, strong) MKTileOverlay *tileOverlay; +@property (nonatomic, strong) MKTileOverlayRenderer *renderer; + +@property (nonatomic, copy) NSString *pathTemplate; +@property (nonatomic, assign) CGFloat tileSize; + +#pragma mark MKOverlay protocol + +@property(nonatomic, readonly) CLLocationCoordinate2D coordinate; +@property(nonatomic, readonly) MKMapRect boundingMapRect; +- (BOOL)canReplaceMapContent; + +@end + diff --git a/lib/ios/AirMaps/AIRMapMbTile.m b/lib/ios/AirMaps/AIRMapMbTile.m new file mode 100644 index 000000000..d63f44d1d --- /dev/null +++ b/lib/ios/AirMaps/AIRMapMbTile.m @@ -0,0 +1,68 @@ +// +// AIRMapMbTile.m +// AirMaps +// +// Created by Christoph Lambio on 28/03/2018. +// Based on AIRMapLocalTile.m +// Copyright (c) 2017 Christopher. All rights reserved. +// + +#import "AIRMapMbTile.h" +#import +#import "AIRMapMbTileOverlay.h" + +@implementation AIRMapMbTile { + BOOL _pathTemplateSet; + BOOL _tileSizeSet; +} + +- (void)setPathTemplate:(NSString *)pathTemplate{ + _pathTemplate = pathTemplate; + _pathTemplateSet = YES; + [self createTileOverlayAndRendererIfPossible]; + [self update]; +} + +- (void)setTileSize:(CGFloat)tileSize{ + _tileSize = tileSize; + _tileSizeSet = YES; + [self createTileOverlayAndRendererIfPossible]; + [self update]; +} + +- (void) createTileOverlayAndRendererIfPossible +{ + if (!_pathTemplateSet || !_tileSizeSet) return; + self.tileOverlay = [[AIRMapMbTileOverlay alloc] initWithURLTemplate:self.pathTemplate]; + self.tileOverlay.canReplaceMapContent = YES; + self.tileOverlay.tileSize = CGSizeMake(_tileSize, _tileSize); + self.renderer = [[MKTileOverlayRenderer alloc] initWithTileOverlay:self.tileOverlay]; +} + +- (void) update +{ + if (!_renderer) return; + + if (_map == nil) return; + [_map removeOverlay:self]; + [_map addOverlay:self level:MKOverlayLevelAboveLabels]; +} + +#pragma mark MKOverlay implementation + +- (CLLocationCoordinate2D) coordinate +{ + return self.tileOverlay.coordinate; +} + +- (MKMapRect) boundingMapRect +{ + return self.tileOverlay.boundingMapRect; +} + +- (BOOL)canReplaceMapContent +{ + return self.tileOverlay.canReplaceMapContent; +} + +@end diff --git a/lib/ios/AirMaps/AIRMapMbTileManager.h b/lib/ios/AirMaps/AIRMapMbTileManager.h new file mode 100644 index 000000000..2a81982e8 --- /dev/null +++ b/lib/ios/AirMaps/AIRMapMbTileManager.h @@ -0,0 +1,14 @@ +// +// AIRMapMbTileManager.h +// AirMaps +// +// Created by Christoph Lambio on 27/03/2018. +// Based on AIRMapLocalTileManager.h +// Copyright (c) 2017 Christopher. All rights reserved. +// + +#import + +@interface AIRMapMbTileManager : RCTViewManager + +@end diff --git a/lib/ios/AirMaps/AIRMapMbTileManager.m b/lib/ios/AirMaps/AIRMapMbTileManager.m new file mode 100644 index 000000000..5d815e608 --- /dev/null +++ b/lib/ios/AirMaps/AIRMapMbTileManager.m @@ -0,0 +1,40 @@ +// +// AIRMapMbTileManager.m +// AirMaps +// +// Created by Christoph Lambio on 27/03/2018. +// Based on AIRMapLocalTileManager.m +// Copyright (c) 2017 Christopher. All rights reserved. +// + +#import +#import +#import +#import +#import +#import +#import "AIRMapMarker.h" +#import "AIRMapMbTile.h" + +#import "AIRMapMbTileManager.h" + +@interface AIRMapMbTileManager() + +@end + +@implementation AIRMapMbTileManager + + +RCT_EXPORT_MODULE() + +- (UIView *)view +{ + AIRMapMbTile *tile = [AIRMapMbTile new]; + return tile; +} + +RCT_EXPORT_VIEW_PROPERTY(pathTemplate, NSString) +RCT_EXPORT_VIEW_PROPERTY(tileSize, CGFloat) + +@end + diff --git a/lib/ios/AirMaps/AIRMapMbTileOverlay.h b/lib/ios/AirMaps/AIRMapMbTileOverlay.h new file mode 100644 index 000000000..18b5d4791 --- /dev/null +++ b/lib/ios/AirMaps/AIRMapMbTileOverlay.h @@ -0,0 +1,15 @@ +// +// AIRMapMbTileOverlay.h +// Pods +// +// Created by Christoph Lambio on 28/03/2018. +// Based on AIRMapLocalTileOverlay.h +// Copyright by (c) by Peter Zavadsky on. +// + +#import + +@interface AIRMapMbTileOverlay : MKTileOverlay + +@end + diff --git a/lib/ios/AirMaps/AIRMapMbTileOverlay.m b/lib/ios/AirMaps/AIRMapMbTileOverlay.m new file mode 100644 index 000000000..4a87eab6f --- /dev/null +++ b/lib/ios/AirMaps/AIRMapMbTileOverlay.m @@ -0,0 +1,40 @@ +// +// AIRMapMbTileOverlay.m +// Pods-AirMapsExplorer +// +// Created by Christoph Lambio on 28/03/2018 +// Based on AIRMapLocalTileOverlay.m +// Copyright (c) by Peter Zavadsky. +// + +#import "AIRMapMbTileOverlay.h" +#import "FMDatabase.h" + +@interface AIRMapMbTileOverlay () + +@end + +@implementation AIRMapMbTileOverlay + + +-(void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *, NSError *))result { + FMDatabase *offlineDataDatabase = [FMDatabase databaseWithPath:self.URLTemplate]; + [offlineDataDatabase open]; + NSMutableString *query = [NSMutableString stringWithString: @"SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y};"]; + [query replaceCharactersInRange: [query rangeOfString: @"{z}"] withString:[NSString stringWithFormat:@"%li", path.z]]; + [query replaceCharactersInRange: [query rangeOfString: @"{x}"] withString:[NSString stringWithFormat:@"%li", path.x]]; + [query replaceCharactersInRange: [query rangeOfString: @"{y}"] withString:[NSString stringWithFormat:@"%li", path.y]]; + FMResultSet *databaseResult = [offlineDataDatabase executeQuery:query]; + if ([databaseResult next]) { + NSData *tile = [databaseResult dataForColumn:@"tile_data"]; + [offlineDataDatabase close]; + result(tile,nil); + } else { + [offlineDataDatabase close]; + result(nil,nil); + } +} + + +@end + diff --git a/lib/ios/AirMaps/fmdb/FMDB.h b/lib/ios/AirMaps/fmdb/FMDB.h new file mode 100644 index 000000000..1ff546504 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDB.h @@ -0,0 +1,10 @@ +#import + +FOUNDATION_EXPORT double FMDBVersionNumber; +FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; + +#import "FMDatabase.h" +#import "FMResultSet.h" +#import "FMDatabaseAdditions.h" +#import "FMDatabaseQueue.h" +#import "FMDatabasePool.h" diff --git a/lib/ios/AirMaps/fmdb/FMDatabase.h b/lib/ios/AirMaps/fmdb/FMDatabase.h new file mode 100644 index 000000000..b779d542e --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabase.h @@ -0,0 +1,1360 @@ +#import +#import "FMResultSet.h" +#import "FMDatabasePool.h" + +NS_ASSUME_NONNULL_BEGIN + +#if ! __has_feature(objc_arc) + #define FMDBAutorelease(__v) ([__v autorelease]); + #define FMDBReturnAutoreleased FMDBAutorelease + + #define FMDBRetain(__v) ([__v retain]); + #define FMDBReturnRetained FMDBRetain + + #define FMDBRelease(__v) ([__v release]); + + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); +#else + // -fobjc-arc + #define FMDBAutorelease(__v) + #define FMDBReturnAutoreleased(__v) (__v) + + #define FMDBRetain(__v) + #define FMDBReturnRetained(__v) (__v) + + #define FMDBRelease(__v) + +// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects +// and will participate in ARC. +// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. + #if OS_OBJECT_USE_OBJC + #define FMDBDispatchQueueRelease(__v) + #else + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); + #endif +#endif + +#if !__has_feature(objc_instancetype) + #define instancetype id +#endif + + +typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); + + +/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. + + ### Usage + The three main classes in FMDB are: + + - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. + - `` - Represents the results of executing a query on an `FMDatabase`. + - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. + + ### See also + + - `` - A pool of `FMDatabase` objects. + - `` - A wrapper for `sqlite_stmt`. + + ### External links + + - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation + - [SQLite web site](http://sqlite.org/) + - [FMDB mailing list](http://groups.google.com/group/fmdb) + - [SQLite FAQ](http://www.sqlite.org/faq.html) + + @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. + + */ + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-interface-ivars" + + +@interface FMDatabase : NSObject + +///----------------- +/// @name Properties +///----------------- + +/** Whether should trace execution */ + +@property (atomic, assign) BOOL traceExecution; + +/** Whether checked out or not */ + +@property (atomic, assign) BOOL checkedOut; + +/** Crash on errors */ + +@property (atomic, assign) BOOL crashOnErrors; + +/** Logs errors */ + +@property (atomic, assign) BOOL logsErrors; + +/** Dictionary of cached statements */ + +@property (atomic, retain, nullable) NSMutableDictionary *cachedStatements; + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithPath:(NSString * _Nullable)inPath; + +/** Create a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param url The local file URL (not remote URL) of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithURL:(NSURL * _Nullable)url; + +/** Initialize a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param path Path of database file. + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithPath:(NSString * _Nullable)path; + +/** Initialize a `FMDatabase` object. + + An `FMDatabase` is created with a local file URL to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param url The file `NSURL` of database file. + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +///----------------------------------- +/// @name Opening and closing database +///----------------------------------- + +/** Opening a new database connection + + The database is opened for reading and writing, and is created if it does not already exist. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) + @see openWithFlags: + @see close + */ + +- (BOOL)open; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName; + +/** Closing a database connection + + @return `YES` if success, `NO` on error. + + @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) + @see open + @see openWithFlags: + */ + +- (BOOL)close; + +/** Test to see if we have a good connection to the database. + + This will confirm whether: + + - is database open + - if open, it will try a simple SELECT statement and confirm that it succeeds. + + @return `YES` if everything succeeds, `NO` on failure. + */ + +@property (nonatomic, readonly) BOOL goodConnection; + + +///---------------------- +/// @name Perform updates +///---------------------- + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + */ + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable *)outErr, ...; + +/** Execute single update statement + + @see executeUpdate:withErrorAndBindings: + + @warning **Deprecated**: Please use `` instead. + */ + +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable*)outErr, ... __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (BOOL)executeUpdate:(NSString*)sql, ...; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate: + @see lastError + @see lastErrorCode + @see lastErrorMessage + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. + */ + +- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate:values:error: + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + + `func executeUpdate(sql: String, values: [Any]?) throws -> Bool` + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage +*/ + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; + + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param args A `va_list` of arguments. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; + +/** Execute multiple SQL statements + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeStatements:withResultBlock: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql; + +/** Execute multiple SQL statements with callback handler + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed. + @param block A block that will be called for any result sets returned by any SQL statements. + Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), + non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. + This may be `nil` if you don't care to receive any results. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, + ``, or `` for diagnostic information regarding the failure. + + @see executeStatements: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock _Nullable)block; + +/** Last insert rowid + + Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. + + This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. + + @return The rowid of the last inserted row. + + @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) + + */ + +@property (nonatomic, readonly) int64_t lastInsertRowId; + +/** The number of rows changed by prior SQL statement. + + This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. + + @return The number of rows changed by prior SQL statement. + + @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) + + */ + +@property (nonatomic, readonly) int changes; + + +///------------------------- +/// @name Retrieving results +///------------------------- + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString*)sql, ...; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeQuery: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. + + */ + +- (FMResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see -executeQuery:values:error: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + + `func executeQuery(sql: String, values: [Any]?) throws -> FMResultSet!` + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. + + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments; + + +// Documentation forthcoming. +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args; + +///------------------- +/// @name Transactions +///------------------- + +/** Begin a transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginDeferredTransaction + @see isInTransaction + */ + +- (BOOL)beginTransaction; + +/** Begin a deferred transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see isInTransaction + */ + +- (BOOL)beginDeferredTransaction; + +/** Commit a transaction + + Commit a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see rollback + @see isInTransaction + */ + +- (BOOL)commit; + +/** Rollback a transaction + + Rollback a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see isInTransaction + */ + +- (BOOL)rollback; + +/** Identify whether currently in a transaction or not + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see rollback + */ + +@property (nonatomic, readonly) BOOL isInTransaction; + +- (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead"); + + +///---------------------------------------- +/// @name Cached statements and result sets +///---------------------------------------- + +/** Clear cached statements */ + +- (void)clearCachedStatements; + +/** Close all open result sets */ + +- (void)closeOpenResultSets; + +/** Whether database has any open result sets + + @return `YES` if there are open result sets; `NO` if not. + */ + +@property (nonatomic, readonly) BOOL hasOpenResultSets; + +/** Whether should cache statements or not + */ + +@property (nonatomic) BOOL shouldCacheStatements; + +/** Interupt pending database operation + + This method causes any pending database operation to abort and return at its earliest opportunity + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + */ + +- (BOOL)interrupt; + +///------------------------- +/// @name Encryption methods +///------------------------- + +/** Set encryption key. + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKey:(NSString*)key; + +/** Reset encryption key + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekey:(NSString*)key; + +/** Set encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKeyWithData:(NSData *)keyData; + +/** Reset encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekeyWithData:(NSData *)keyData; + + +///------------------------------ +/// @name General inquiry methods +///------------------------------ + +/** The path of the database file + */ + +@property (nonatomic, readonly, nullable) NSString *databasePath; + +/** The file URL of the database file. + */ + +@property (nonatomic, readonly, nullable) NSURL *databaseURL; + +/** The underlying SQLite handle + + @return The `sqlite3` pointer. + + */ + +@property (nonatomic, readonly) void *sqliteHandle; + + +///----------------------------- +/// @name Retrieving error codes +///----------------------------- + +/** Last error message + + Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return `NSString` of the last error message. + + @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorCode + @see lastError + + */ + +- (NSString*)lastErrorMessage; + +/** Last error code + + Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastErrorCode; + +/** Last extended error code + + Returns the numeric extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last extended error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see [2. Primary Result Codes versus Extended Result Codes](http://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes) + @see [5. Extended Result Code List](http://sqlite.org/rescode.html#extrc) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastExtendedErrorCode; + +/** Had error + + @return `YES` if there was an error, `NO` if no error. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)hadError; + +/** Last error + + @return `NSError` representing the last error. + + @see lastErrorCode + @see lastErrorMessage + + */ + +- (NSError *)lastError; + + +// description forthcoming +@property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval; + + +///------------------ +/// @name Save points +///------------------ + +/** Start save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + */ + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Release save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Roll back to save point + + @param name Name of save point. + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + + */ + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Start save point + + @param block Block of code to perform from within save point. + + @return The NSError corresponding to the error, if any. If no error, returns `nil`. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block; + +///---------------------------- +/// @name SQLite library status +///---------------------------- + +/** Test to see if the library is threadsafe + + @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. + + @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) + */ + ++ (BOOL)isSQLiteThreadSafe; + +/** Run-time library version numbers + + @return The sqlite library version string. + + @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) + */ + ++ (NSString*)sqliteLibVersion; + + ++ (NSString*)FMDBUserVersion; + ++ (SInt32)FMDBVersion; + + +///------------------------ +/// @name Make SQL function +///------------------------ + +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. + + For example: + + [db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { + SqliteValueType type = [self.db valueType:argv[0]]; + if (type == SqliteValueTypeNull) { + [self.db resultNullInContext:context]; + return; + } + if (type != SqliteValueTypeText) { + [self.db resultError:@"Expected text" context:context]; + return; + } + NSString *string = [self.db valueString:argv[0]]; + NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; + [self.db resultString:result context:context]; + }]; + + FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"]; + NSAssert(rs, @"Error %@", [db lastErrorMessage]); + + @param name Name of function. + + @param arguments Maximum number of parameters. + + @param block The block of code for the function. + + @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) + */ + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block; + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:"); + +typedef NS_ENUM(int, SqliteValueType) { + SqliteValueTypeInteger = 1, + SqliteValueTypeFloat = 2, + SqliteValueTypeText = 3, + SqliteValueTypeBlob = 4, + SqliteValueTypeNull = 5 +}; + +- (SqliteValueType)valueType:(void *)argv; + +/** + Get integer value of parameter in custom function. + + @param value The argument whose value to return. + @return The integer value. + + @see makeFunctionNamed:arguments:block: + */ +- (int)valueInt:(void *)value; + +/** + Get long value of parameter in custom function. + + @param value The argument whose value to return. + @return The long value. + + @see makeFunctionNamed:arguments:block: + */ +- (long long)valueLong:(void *)value; + +/** + Get double value of parameter in custom function. + + @param value The argument whose value to return. + @return The double value. + + @see makeFunctionNamed:arguments:block: + */ +- (double)valueDouble:(void *)value; + +/** + Get `NSData` value of parameter in custom function. + + @param value The argument whose value to return. + @return The data object. + + @see makeFunctionNamed:arguments:block: + */ +- (NSData * _Nullable)valueData:(void *)value; + +/** + Get string value of parameter in custom function. + + @param value The argument whose value to return. + @return The string value. + + @see makeFunctionNamed:arguments:block: + */ +- (NSString * _Nullable)valueString:(void *)value; + +/** + Return null value from custom function. + + @param context The context to which the null value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:)); + +/** + Return integer value from custom function. + + @param value The integer value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultInt:(int) value context:(void *)context; + +/** + Return long value from custom function. + + @param value The long value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultLong:(long long)value context:(void *)context; + +/** + Return double value from custom function. + + @param value The double value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultDouble:(double)value context:(void *)context; + +/** + Return `NSData` object from custom function. + + @param data The `NSData` object to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultData:(NSData *)data context:(void *)context; + +/** + Return string value from custom function. + + @param value The string value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultString:(NSString *)value context:(void *)context; + +/** + Return error string from custom function. + + @param error The error string to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultError:(NSString *)error context:(void *)context; + +/** + Return error code from custom function. + + @param errorCode The integer error code to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorCode:(int)errorCode context:(void *)context; + +/** + Report memory error in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:)); + +/** + Report that string or BLOB is too long to represent in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:)); + +///--------------------- +/// @name Date formatter +///--------------------- + +/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. + + Use this method to generate values to set the dateFormat property. + + Example: + + myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + @param format A valid NSDateFormatter format string. + + @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. + + */ + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format; + +/** Test whether the database has a date formatter assigned. + + @return `YES` if there is a date formatter; `NO` if not. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (BOOL)hasDateFormatter; + +/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. + + @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. + */ + +- (void)setDateFormat:(NSDateFormatter *)format; + +/** Convert the supplied NSString to NSDate, using the current database formatter. + + @param s `NSString` to convert to `NSDate`. + + @return The `NSDate` object; or `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSDate * _Nullable)dateFromString:(NSString *)s; + +/** Convert the supplied NSDate to NSString, using the current database formatter. + + @param date `NSDate` of date to convert to `NSString`. + + @return The `NSString` representation of the date; `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSString *)stringFromDate:(NSDate *)date; + +@end + + +/** Objective-C wrapper for `sqlite3_stmt` + + This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. + + ### See also + + - `` + - `` + - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@interface FMStatement : NSObject { + void *_statement; + NSString *_query; + long _useCount; + BOOL _inUse; +} + +///----------------- +/// @name Properties +///----------------- + +/** Usage count */ + +@property (atomic, assign) long useCount; + +/** SQL statement */ + +@property (atomic, retain) NSString *query; + +/** SQLite sqlite3_stmt + + @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@property (atomic, assign) void *statement; + +/** Indication of whether the statement is in use */ + +@property (atomic, assign) BOOL inUse; + +///---------------------------- +/// @name Closing and Resetting +///---------------------------- + +/** Close statement */ + +- (void)close; + +/** Reset statement */ + +- (void)reset; + +@end + +#pragma clang diagnostic pop + +NS_ASSUME_NONNULL_END diff --git a/lib/ios/AirMaps/fmdb/FMDatabase.m b/lib/ios/AirMaps/fmdb/FMDatabase.m new file mode 100644 index 000000000..493e772ea --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabase.m @@ -0,0 +1,1596 @@ +#import "FMDatabase.h" +#import "unistd.h" +#import + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () { + void* _db; + BOOL _isExecutingStatement; + NSTimeInterval _startBusyRetryTime; + + NSMutableSet *_openResultSets; + NSMutableSet *_openFunctions; + + NSDateFormatter *_dateFormat; +} + +NS_ASSUME_NONNULL_BEGIN + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; +- (BOOL)executeUpdate:(NSString *)sql error:(NSError * _Nullable *)outErr withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; + +NS_ASSUME_NONNULL_END + +@end + +@implementation FMDatabase + +// Because these two properties have all of their accessor methods implemented, +// we have to synthesize them to get the corresponding ivars. The rest of the +// properties have their ivars synthesized automatically for us. + +@synthesize shouldCacheStatements = _shouldCacheStatements; +@synthesize maxBusyRetryTimeInterval = _maxBusyRetryTimeInterval; + +#pragma mark FMDatabase instantiation and deallocation + ++ (instancetype)databaseWithPath:(NSString *)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databaseWithURL:(NSURL *)url { + return FMDBReturnAutoreleased([[self alloc] initWithURL:url]); +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)path { + + assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. + + self = [super init]; + + if (self) { + _databasePath = [path copy]; + _openResultSets = [[NSMutableSet alloc] init]; + _db = nil; + _logsErrors = YES; + _crashOnErrors = NO; + _maxBusyRetryTimeInterval = 2; + } + + return self; +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_openResultSets); + FMDBRelease(_cachedStatements); + FMDBRelease(_dateFormat); + FMDBRelease(_databasePath); + FMDBRelease(_openFunctions); + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (NSURL *)databaseURL { + return _databasePath ? [NSURL fileURLWithPath:_databasePath] : nil; +} + ++ (NSString*)FMDBUserVersion { + return @"2.7.2"; +} + +// returns 0x0240 for version 2.4. This makes it super easy to do things like: +// /* need to make sure to do X with FMDB version 2.4 or later */ +// if ([FMDatabase FMDBVersion] >= 0x0240) { … } + ++ (SInt32)FMDBVersion { + + // we go through these hoops so that we only have to change the version number in a single spot. + static dispatch_once_t once; + static SInt32 FMDBVersionVal = 0; + + dispatch_once(&once, ^{ + NSString *prodVersion = [self FMDBUserVersion]; + + if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { + prodVersion = [prodVersion stringByAppendingString:@".0"]; + } + + NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""]; + + char *e = nil; + FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16); + + }); + + return FMDBVersionVal; +} + +#pragma mark SQLite information + ++ (NSString*)sqliteLibVersion { + return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; +} + ++ (BOOL)isSQLiteThreadSafe { + // make sure to read the sqlite headers on this guy! + return sqlite3_threadsafe() != 0; +} + +- (void*)sqliteHandle { + return _db; +} + +- (const char*)sqlitePath { + + if (!_databasePath) { + return ":memory:"; + } + + if ([_databasePath length] == 0) { + return ""; // this creates a temporary database (it's an sqlite thing). + } + + return [_databasePath fileSystemRepresentation]; + +} + +#pragma mark Open and close database + +- (BOOL)open { + if (_db) { + return YES; + } + + int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + + return YES; +} + +- (BOOL)openWithFlags:(int)flags { + return [self openWithFlags:flags vfs:nil]; +} +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { +#if SQLITE_VERSION_NUMBER >= 3005000 + if (_db) { + return YES; + } + + int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + return YES; +#else + NSLog(@"openWithFlags requires SQLite 3.5"); + return NO; +#endif +} + + +- (BOOL)close { + + [self clearCachedStatements]; + [self closeOpenResultSets]; + + if (!_db) { + return YES; + } + + int rc; + BOOL retry; + BOOL triedFinalizingOpenStatements = NO; + + do { + retry = NO; + rc = sqlite3_close(_db); + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + if (!triedFinalizingOpenStatements) { + triedFinalizingOpenStatements = YES; + sqlite3_stmt *pStmt; + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { + NSLog(@"Closing leaked statement"); + sqlite3_finalize(pStmt); + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + return YES; +} + +#pragma mark Busy handler routines + +// NOTE: appledoc seems to choke on this function for some reason; +// so when generating documentation, you might want to ignore the +// .m files so that it only documents the public interfaces outlined +// in the .h files. +// +// This is a known appledoc bug that it has problems with C functions +// within a class implementation, but for some reason, only this +// C function causes problems; the rest don't. Anyway, ignoring the .m +// files with appledoc will prevent this problem from occurring. + +static int FMDBDatabaseBusyHandler(void *f, int count) { + FMDatabase *self = (__bridge FMDatabase*)f; + + if (count == 0) { + self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; + return 1; + } + + NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); + + if (delta < [self maxBusyRetryTimeInterval]) { + int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; + int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); + if (actualSleepInMilliseconds != requestedSleepInMillseconds) { + NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); + } + return 1; + } + + return 0; +} + +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { + + _maxBusyRetryTimeInterval = timeout; + + if (!_db) { + return; + } + + if (timeout > 0) { + sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self)); + } + else { + // turn it off otherwise + sqlite3_busy_handler(_db, nil, nil); + } +} + +- (NSTimeInterval)maxBusyRetryTimeInterval { + return _maxBusyRetryTimeInterval; +} + + +// we no longer make busyRetryTimeout public +// but for folks who don't bother noticing that the interface to FMDatabase changed, +// we'll still implement the method so they don't get suprise crashes +- (int)busyRetryTimeout { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); + return -1; +} + +- (void)setBusyRetryTimeout:(int)i { +#pragma unused(i) + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); +} + +#pragma mark Result set functions + +- (BOOL)hasOpenResultSets { + return [_openResultSets count] > 0; +} + +- (void)closeOpenResultSets { + + //Copy the set so we don't get mutation errors + NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + + [rs setParentDB:nil]; + [rs close]; + + [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; + } +} + +- (void)resultSetDidClose:(FMResultSet *)resultSet { + NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; + + [_openResultSets removeObject:setValue]; +} + +#pragma mark Cached statements + +- (void)clearCachedStatements { + + for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { + for (FMStatement *statement in [statements allObjects]) { + [statement close]; + } + } + + [_cachedStatements removeAllObjects]; +} + +- (FMStatement*)cachedStatementForQuery:(NSString*)query { + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + + return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) { + + *stop = ![statement inUse]; + return *stop; + + }] anyObject]; +} + + +- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query { + + query = [query copy]; // in case we got handed in a mutable string... + [statement setQuery:query]; + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + if (!statements) { + statements = [NSMutableSet set]; + } + + [statements addObject:statement]; + + [_cachedStatements setObject:statements forKey:query]; + + FMDBRelease(query); +} + +#pragma mark Key routines + +- (BOOL)rekey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self rekeyWithData:keyData]; +} + +- (BOOL)rekeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]); + + if (rc != SQLITE_OK) { + NSLog(@"error on rekey: %d", rc); + NSLog(@"%@", [self lastErrorMessage]); + } + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +- (BOOL)setKey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self setKeyWithData:keyData]; +} + +- (BOOL)setKeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]); + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +#pragma mark Date routines + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format { + + NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]); + result.dateFormat = format; + result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); + return result; +} + + +- (BOOL)hasDateFormatter { + return _dateFormat != nil; +} + +- (void)setDateFormat:(NSDateFormatter *)format { + FMDBAutorelease(_dateFormat); + _dateFormat = FMDBReturnRetained(format); +} + +- (NSDate *)dateFromString:(NSString *)s { + return [_dateFormat dateFromString:s]; +} + +- (NSString *)stringFromDate:(NSDate *)date { + return [_dateFormat stringFromDate:date]; +} + +#pragma mark State of database + +- (BOOL)goodConnection { + + if (!_db) { + return NO; + } + + FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; + + if (rs) { + [rs close]; + return YES; + } + + return NO; +} + +- (void)warnInUse { + NSLog(@"The FMDatabase %@ is currently in use.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is currently in use.", self); + abort(); + } +#endif +} + +- (BOOL)databaseExists { + + if (!_db) { + + NSLog(@"The FMDatabase %@ is not open.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is not open.", self); + abort(); + } +#endif + + return NO; + } + + return YES; +} + +#pragma mark Error routines + +- (NSString *)lastErrorMessage { + return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; +} + +- (BOOL)hadError { + int lastErrCode = [self lastErrorCode]; + + return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); +} + +- (int)lastErrorCode { + return sqlite3_errcode(_db); +} + +- (int)lastExtendedErrorCode { + return sqlite3_extended_errcode(_db); +} + +- (NSError*)errorWithMessage:(NSString *)message { + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; + + return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; +} + +- (NSError*)lastError { + return [self errorWithMessage:[self lastErrorMessage]]; +} + +#pragma mark Update information routines + +- (sqlite_int64)lastInsertRowId { + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + sqlite_int64 ret = sqlite3_last_insert_rowid(_db); + + _isExecutingStatement = NO; + + return ret; +} + +- (int)changes { + if (_isExecutingStatement) { + [self warnInUse]; + return 0; + } + + _isExecutingStatement = YES; + + int ret = sqlite3_changes(_db); + + _isExecutingStatement = NO; + + return ret; +} + +#pragma mark SQL manipulation + +- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { + + if ((!obj) || ((NSNull *)obj == [NSNull null])) { + sqlite3_bind_null(pStmt, idx); + } + + // FIXME - someday check the return codes on these binds. + else if ([obj isKindOfClass:[NSData class]]) { + const void *bytes = [obj bytes]; + if (!bytes) { + // it's an empty NSData object, aka [NSData data]. + // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. + bytes = ""; + } + sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC); + } + else if ([obj isKindOfClass:[NSDate class]]) { + if (self.hasDateFormatter) + sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC); + else + sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); + } + else if ([obj isKindOfClass:[NSNumber class]]) { + + if (strcmp([obj objCType], @encode(char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj charValue]); + } + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); + } + else if (strcmp([obj objCType], @encode(short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj shortValue]); + } + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); + } + else if (strcmp([obj objCType], @encode(int)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj intValue]); + } + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); + } + else if (strcmp([obj objCType], @encode(long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); + } + else if (strcmp([obj objCType], @encode(long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); + } + else if (strcmp([obj objCType], @encode(float)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj floatValue]); + } + else if (strcmp([obj objCType], @encode(double)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj doubleValue]); + } + else if (strcmp([obj objCType], @encode(BOOL)) == 0) { + sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } +} + +- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { + + NSUInteger length = [sql length]; + unichar last = '\0'; + for (NSUInteger i = 0; i < length; ++i) { + id arg = nil; + unichar current = [sql characterAtIndex:i]; + unichar add = current; + if (last == '%') { + switch (current) { + case '@': + arg = va_arg(args, id); + break; + case 'c': + // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; + break; + case 's': + arg = [NSString stringWithUTF8String:va_arg(args, char*)]; + break; + case 'd': + case 'D': + case 'i': + arg = [NSNumber numberWithInt:va_arg(args, int)]; + break; + case 'u': + case 'U': + arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; + break; + case 'h': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; + } + else { + i--; + } + break; + case 'q': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + break; + case 'f': + arg = [NSNumber numberWithDouble:va_arg(args, double)]; + break; + case 'g': + // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' + arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; + break; + case 'l': + i++; + if (i < length) { + unichar next = [sql characterAtIndex:i]; + if (next == 'l') { + i++; + if (i < length && [sql characterAtIndex:i] == 'd') { + //%lld + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + //%llu + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + } + else if (next == 'd') { + //%ld + arg = [NSNumber numberWithLong:va_arg(args, long)]; + } + else if (next == 'u') { + //%lu + arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; + } + else { + i--; + } + } + else { + i--; + } + break; + default: + // something else that we can't interpret. just pass it on through like normal + break; + } + } + else if (current == '%') { + // percent sign; skip this character + add = '\0'; + } + + if (arg != nil) { + [cleanedSQL appendString:@"?"]; + [arguments addObject:arg]; + } + else if (add == (unichar)'@' && last == (unichar) '%') { + [cleanedSQL appendFormat:@"NULL"]; + } + else if (add != '\0') { + [cleanedSQL appendFormat:@"%C", add]; + } + last = current; + } +} + +#pragma mark Execute queries + +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return 0x00; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return 0x00; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *statement = 0x00; + FMResultSet *rs = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeQuery: %@", self, sql); + } + + if (_shouldCacheStatements) { + statement = [self cachedStatementForQuery:sql]; + pStmt = statement ? [statement statement] : 0x00; + [statement reset]; + } + + if (!pStmt) { + + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + // increment the binding count, so our check below works out + idx++; + } + else { + NSLog(@"Could not find index for %@", dictionaryKey); + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + if (idx != queryCount) { + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + + FMDBRetain(statement); // to balance the release below + + if (!statement) { + statement = [[FMStatement alloc] init]; + [statement setStatement:pStmt]; + + if (_shouldCacheStatements && sql) { + [self setCachedStatement:statement forQuery:sql]; + } + } + + // the statement gets closed in rs's dealloc or [rs close]; + rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self]; + [rs setQuery:sql]; + + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; + [_openResultSets addObject:openResultSet]; + + [statement setUseCount:[statement useCount] + 1]; + + FMDBRelease(statement); + + _isExecutingStatement = NO; + + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeQuery:sql withArgumentsInArray:arguments]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil]; + if (!rs && error) { + *error = [self lastError]; + } + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +#pragma mark Execute updates + +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return NO; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *cachedStmt = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeUpdate: %@", self, sql); + } + + if (_shouldCacheStatements) { + cachedStmt = [self cachedStatementForQuery:sql]; + pStmt = cachedStmt ? [cachedStmt statement] : 0x00; + [cachedStmt reset]; + } + + if (!pStmt) { + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + sqlite3_finalize(pStmt); + + _isExecutingStatement = NO; + return NO; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + + // increment the binding count, so our check below works out + idx++; + } + else { + NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey]; + + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + + if (idx != queryCount) { + NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql]; + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return NO; + } + + /* Call sqlite3_step() to run the virtual machine. Since the SQL being + ** executed is not a SELECT statement, we assume no data will be returned. + */ + + rc = sqlite3_step(pStmt); + + if (SQLITE_DONE == rc) { + // all is well, let's return. + } + else if (SQLITE_INTERRUPT == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step. Query was interrupted (%d: %s) SQLITE_INTERRUPT", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (rc == SQLITE_ROW) { + NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql]; + if (_logsErrors) { + NSLog(@"%@", message); + NSLog(@"DB Query: %@", sql); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + else { + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + if (SQLITE_ERROR == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else { + // wtf? + if (_logsErrors) { + NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + } + + if (_shouldCacheStatements && !cachedStmt) { + cachedStmt = [[FMStatement alloc] init]; + + [cachedStmt setStatement:pStmt]; + + [self setCachedStatement:cachedStmt forQuery:sql]; + + FMDBRelease(cachedStmt); + } + + int closeErrorCode; + + if (cachedStmt) { + [cachedStmt setUseCount:[cachedStmt useCount] + 1]; + closeErrorCode = sqlite3_reset(pStmt); + } + else { + /* Finalize the virtual machine. This releases all memory and other + ** resources allocated by the sqlite3_prepare() call above. + */ + closeErrorCode = sqlite3_finalize(pStmt); + } + + if (closeErrorCode != SQLITE_OK) { + if (_logsErrors) { + NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + + _isExecutingStatement = NO; + return (rc == SQLITE_DONE || rc == SQLITE_OK); +} + + +- (BOOL)executeUpdate:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +- (BOOL)executeUpdateWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeUpdate:sql withArgumentsInArray:arguments]; +} + + +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { + + if (!theBlockAsVoid) { + return SQLITE_OK; + } + + int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); + + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; + + for (NSInteger i = 0; i < columns; i++) { + NSString *key = [NSString stringWithUTF8String:names[i]]; + id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; + [dictionary setObject:value forKey:key]; + } + + return execCallbackBlock(dictionary); +} + +- (BOOL)executeStatements:(NSString *)sql { + return [self executeStatements:sql withResultBlock:nil]; +} + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block { + + int rc; + char *errmsg = nil; + + rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); + + if (errmsg && [self logsErrors]) { + NSLog(@"Error inserting batch: %s", errmsg); + sqlite3_free(errmsg); + } + + return (rc == SQLITE_OK); +} + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +#pragma clang diagnostic pop + +#pragma mark Transactions + +- (BOOL)rollback { + BOOL b = [self executeUpdate:@"rollback transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)commit { + BOOL b = [self executeUpdate:@"commit transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)beginDeferredTransaction { + + BOOL b = [self executeUpdate:@"begin deferred transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)beginTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)inTransaction { + return _isInTransaction; +} + +- (BOOL)interrupt +{ + if (_db) { + sqlite3_interrupt([self sqliteHandle]); + return YES; + } + return NO; +} + +static NSString *FMDBEscapeSavePointName(NSString *savepointName) { + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; +} + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + NSError *err = 0x00; + + if (![self startSavePointWithName:name error:&err]) { + return err; + } + + if (block) { + block(&shouldRollback); + } + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [self rollbackToSavePointWithName:name error:&err]; + } + [self releaseSavePointWithName:name error:&err]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + + +#pragma mark Cache statements + +- (BOOL)shouldCacheStatements { + return _shouldCacheStatements; +} + +- (void)setShouldCacheStatements:(BOOL)value { + + _shouldCacheStatements = value; + + if (_shouldCacheStatements && !_cachedStatements) { + [self setCachedStatements:[NSMutableDictionary dictionary]]; + } + + if (!_shouldCacheStatements) { + [self setCachedStatements:nil]; + } +} + +#pragma mark Callback function + +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { +#if ! __has_feature(objc_arc) + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); +#else + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); +#endif + if (block) { + @autoreleasepool { + block(context, argc, argv); + } + } +} + +// deprecated because "arguments" parameter is not maximum argument count, but actual argument count. + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block { + [self makeFunctionNamed:name arguments:arguments block:block]; +} + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block { + + if (!_openFunctions) { + _openFunctions = [NSMutableSet new]; + } + + id b = FMDBReturnAutoreleased([block copy]); + + [_openFunctions addObject:b]; + + /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ +#if ! __has_feature(objc_arc) + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#else + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#endif +} + +- (SqliteValueType)valueType:(void *)value { + return sqlite3_value_type(value); +} + +- (int)valueInt:(void *)value { + return sqlite3_value_int(value); +} + +- (long long)valueLong:(void *)value { + return sqlite3_value_int64(value); +} + +- (double)valueDouble:(void *)value { + return sqlite3_value_double(value); +} + +- (NSData *)valueData:(void *)value { + const void *bytes = sqlite3_value_blob(value); + int length = sqlite3_value_bytes(value); + return bytes ? [NSData dataWithBytes:bytes length:length] : nil; +} + +- (NSString *)valueString:(void *)value { + const char *cString = (const char *)sqlite3_value_text(value); + return cString ? [NSString stringWithUTF8String:cString] : nil; +} + +- (void)resultNullInContext:(void *)context { + sqlite3_result_null(context); +} + +- (void)resultInt:(int) value context:(void *)context { + sqlite3_result_int(context, value); +} + +- (void)resultLong:(long long)value context:(void *)context { + sqlite3_result_int64(context, value); +} + +- (void)resultDouble:(double)value context:(void *)context { + sqlite3_result_double(context, value); +} + +- (void)resultData:(NSData *)data context:(void *)context { + sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT); +} + +- (void)resultString:(NSString *)value context:(void *)context { + sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT); +} + +- (void)resultError:(NSString *)error context:(void *)context { + sqlite3_result_error(context, [error UTF8String], -1); +} + +- (void)resultErrorCode:(int)errorCode context:(void *)context { + sqlite3_result_error_code(context, errorCode); +} + +- (void)resultErrorNoMemoryInContext:(void *)context { + sqlite3_result_error_nomem(context); +} + +- (void)resultErrorTooBigInContext:(void *)context { + sqlite3_result_error_toobig(context); +} + +@end + + + +@implementation FMStatement + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_query); +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + if (_statement) { + sqlite3_finalize(_statement); + _statement = 0x00; + } + + _inUse = NO; +} + +- (void)reset { + if (_statement) { + sqlite3_reset(_statement); + } + + _inUse = NO; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; +} + +@end + diff --git a/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.h b/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.h new file mode 100644 index 000000000..8ee51c721 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.h @@ -0,0 +1,250 @@ +// +// FMDatabaseAdditions.h +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import +#import "FMDatabase.h" + +NS_ASSUME_NONNULL_BEGIN + +/** Category of additions for `` class. + + ### See also + + - `` + */ + +@interface FMDatabase (FMDatabaseAdditions) + +///---------------------------------------- +/// @name Return results of SQL to variable +///---------------------------------------- + +/** Return `int` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `int` value. + + @note This is not available from Swift. + */ + +- (int)intForQuery:(NSString*)query, ...; + +/** Return `long` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `long` value. + + @note This is not available from Swift. + */ + +- (long)longForQuery:(NSString*)query, ...; + +/** Return `BOOL` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `BOOL` value. + + @note This is not available from Swift. + */ + +- (BOOL)boolForQuery:(NSString*)query, ...; + +/** Return `double` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `double` value. + + @note This is not available from Swift. + */ + +- (double)doubleForQuery:(NSString*)query, ...; + +/** Return `NSString` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSString` value. + + @note This is not available from Swift. + */ + +- (NSString * _Nullable)stringForQuery:(NSString*)query, ...; + +/** Return `NSData` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSData` value. + + @note This is not available from Swift. + */ + +- (NSData * _Nullable)dataForQuery:(NSString*)query, ...; + +/** Return `NSDate` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSDate` value. + + @note This is not available from Swift. + */ + +- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...; + + +// Notice that there's no dataNoCopyForQuery:. +// That would be a bad idea, because we close out the result set, and then what +// happens to the data that we just didn't copy? Who knows, not I. + + +///-------------------------------- +/// @name Schema related operations +///-------------------------------- + +/** Does table exist in database? + + @param tableName The name of the table being looked for. + + @return `YES` if table found; `NO` if not found. + */ + +- (BOOL)tableExists:(NSString*)tableName; + +/** The schema of the database. + + This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: + + - `type` - The type of entity (e.g. table, index, view, or trigger) + - `name` - The name of the object + - `tbl_name` - The name of the table to which the object references + - `rootpage` - The page number of the root b-tree page for tables and indices + - `sql` - The SQL that created the entity + + @return `FMResultSet` of schema; `nil` on error. + + @see [SQLite File Format](http://www.sqlite.org/fileformat.html) + */ + +- (FMResultSet *)getSchema; + +/** The schema of the database. + + This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: + + PRAGMA table_info('employees') + + This will report: + + - `cid` - The column ID number + - `name` - The name of the column + - `type` - The data type specified for the column + - `notnull` - whether the field is defined as NOT NULL (i.e. values required) + - `dflt_value` - The default value for the column + - `pk` - Whether the field is part of the primary key of the table + + @param tableName The name of the table for whom the schema will be returned. + + @return `FMResultSet` of schema; `nil` on error. + + @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) + */ + +- (FMResultSet*)getTableSchema:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + */ + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + + @see columnExists:inTableWithName: + + @warning Deprecated - use `` instead. + */ + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead"); + + +/** Validate SQL statement + + This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. + + @param sql The SQL statement being validated. + + @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. + + @return `YES` if validation succeeded without incident; `NO` otherwise. + + */ + +- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable *)error; + + +///----------------------------------- +/// @name Application identifier tasks +///----------------------------------- + +/** Retrieve application ID + + @return The `uint32_t` numeric value of the application ID. + + @see setApplicationID: + */ + +@property (nonatomic) uint32_t applicationID; + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +/** Retrieve application ID string + + @see setApplicationIDString: + */ + +@property (nonatomic, retain) NSString *applicationIDString; + +#endif + +///----------------------------------- +/// @name user version identifier tasks +///----------------------------------- + +/** Retrieve user version + + @see setUserVersion: + */ + +@property (nonatomic) uint32_t userVersion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.m b/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.m new file mode 100644 index 000000000..208e69e52 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabaseAdditions.m @@ -0,0 +1,245 @@ +// +// FMDatabaseAdditions.m +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" +#import "TargetConditionals.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase (PrivateStuff) +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; +@end + +@implementation FMDatabase (FMDatabaseAdditions) + +#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ +va_list args; \ +va_start(args, query); \ +FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ +va_end(args); \ +if (![resultSet next]) { return (type)0; } \ +type ret = [resultSet sel:0]; \ +[resultSet close]; \ +[resultSet setParentDB:nil]; \ +return ret; + + +- (NSString *)stringForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); +} + +- (int)intForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); +} + +- (long)longForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); +} + +- (BOOL)boolForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); +} + +- (double)doubleForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); +} + +- (NSData*)dataForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); +} + +- (NSDate*)dateForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); +} + + +- (BOOL)tableExists:(NSString*)tableName { + + tableName = [tableName lowercaseString]; + + FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; + + //if at least one next exists, table exists + BOOL returnBool = [rs next]; + + //close and free object + [rs close]; + + return returnBool; +} + +/* + get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + check if table exist in database (patch from OZLB) +*/ +- (FMResultSet*)getSchema { + + //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; + + return rs; +} + +/* + get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] +*/ +- (FMResultSet*)getTableSchema:(NSString*)tableName { + + //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] + FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; + + return rs; +} + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { + + BOOL returnBool = NO; + + tableName = [tableName lowercaseString]; + columnName = [columnName lowercaseString]; + + FMResultSet *rs = [self getTableSchema:tableName]; + + //check if column is present in table schema + while ([rs next]) { + if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { + returnBool = YES; + break; + } + } + + //If this is not done FMDatabase instance stays out of pool + [rs close]; + + return returnBool; +} + + + +- (uint32_t)applicationID { +#if SQLITE_VERSION_NUMBER >= 3007017 + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma application_id"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + + return r; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return 0; +#endif +} + +- (void)setApplicationID:(uint32_t)appID { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +- (NSString*)applicationIDString { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); + + assert([s length] == 6); + + s = [s substringWithRange:NSMakeRange(1, 4)]; + + + return s; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return nil; +#endif +} + +- (void)setApplicationIDString:(NSString*)s { +#if SQLITE_VERSION_NUMBER >= 3007017 + if ([s length] != 4) { + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); + } + + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + +#endif + +- (uint32_t)userVersion { + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma user_version"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + return r; +} + +- (void)setUserVersion:(uint32_t)version { + NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { + return [self columnExists:columnName inTableWithName:tableName]; +} + +#pragma clang diagnostic pop + +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { + sqlite3_stmt *pStmt = NULL; + BOOL validationSucceeded = YES; + + int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0); + if (rc != SQLITE_OK) { + validationSucceeded = NO; + if (error) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain + code:[self lastErrorCode] + userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] + forKey:NSLocalizedDescriptionKey]]; + } + } + + sqlite3_finalize(pStmt); + + return validationSucceeded; +} + +@end diff --git a/lib/ios/AirMaps/fmdb/FMDatabasePool.h b/lib/ios/AirMaps/fmdb/FMDatabasePool.h new file mode 100755 index 000000000..3642f59c5 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabasePool.h @@ -0,0 +1,258 @@ +// +// FMDatabasePool.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FMDatabase; + +/** Pool of `` objects. + + ### See also + + - `` + - `` + + @warning Before using `FMDatabasePool`, please consider using `` instead. + + If you really really really know what you're doing and `FMDatabasePool` is what + you really really need (ie, you're using a read only database), OK you can use + it. But just be careful not to deadlock! + + For an example on deadlocking, search for: + `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` + in the main.m file. + */ + +@interface FMDatabasePool : NSObject + +/** Database path */ + +@property (atomic, copy, nullable) NSString *path; + +/** Delegate object */ + +@property (atomic, assign, nullable) id delegate; + +/** Maximum number of databases to create */ + +@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy, nullable) NSString *vfsName; + + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath; + +/** Create pool using file URL. + + @param url The file `NSURL` of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url; + +/** Create pool using path and specified flags + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create pool using file URL and specified flags + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath; + +/** Create pool using file URL. + + @param url The file `NSURL of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create pool using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Create pool using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +///------------------------------------------------ +/// @name Keeping track of checked in/out databases +///------------------------------------------------ + +/** Number of checked-in databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases; + +/** Number of checked-out databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases; + +/** Total number of databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfOpenDatabases; + +/** Release all databases in pool */ + +- (void)releaseAllDatabases; + +///------------------------------------------ +/// @name Perform database operations in pool +///------------------------------------------ + +/** Synchronously perform database operations in pool. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations in pool using transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using deferred transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using save point. + + @param block The code to be run on the `FMDatabasePool` pool. + + @return `NSError` object if error; `nil` if successful. + + @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. +*/ + +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + + +/** FMDatabasePool delegate category + + This is a category that defines the protocol for the FMDatabasePool delegate + */ + +@interface NSObject (FMDatabasePoolDelegate) + +/** Asks the delegate whether database should be added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + @return `YES` if it should add database to pool; `NO` if not. + + */ + +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; + +/** Tells the delegate that database was added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + */ + +- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; + +@end + +NS_ASSUME_NONNULL_END diff --git a/lib/ios/AirMaps/fmdb/FMDatabasePool.m b/lib/ios/AirMaps/fmdb/FMDatabasePool.m new file mode 100755 index 000000000..41a598589 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabasePool.m @@ -0,0 +1,316 @@ +// +// FMDatabasePool.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +#import "FMDatabasePool.h" +#import "FMDatabase.h" + +@interface FMDatabasePool () { + dispatch_queue_t _lockQueue; + + NSMutableArray *_databaseInPool; + NSMutableArray *_databaseOutPool; +} + +- (void)pushDatabaseBackInPool:(FMDatabase*)db; +- (FMDatabase*)db; + +@end + + +@implementation FMDatabasePool +@synthesize path=_path; +@synthesize delegate=_delegate; +@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; +@synthesize openFlags=_openFlags; + + ++ (instancetype)databasePoolWithPath:(NSString *)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databasePoolWithURL:(NSURL *)url { + return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path]); +} + ++ (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); +} + ++ (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]); +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { + return [self initWithPath:url.path flags:openFlags vfs:vfsName]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + + self = [super init]; + + if (self != nil) { + _path = [aPath copy]; + _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + _databaseInPool = FMDBReturnRetained([NSMutableArray array]); + _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { + return [self initWithPath:url.path flags:openFlags vfs:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath { + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (void)dealloc { + + _delegate = 0x00; + FMDBRelease(_path); + FMDBRelease(_databaseInPool); + FMDBRelease(_databaseOutPool); + FMDBRelease(_vfsName); + + if (_lockQueue) { + FMDBDispatchQueueRelease(_lockQueue); + _lockQueue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + + +- (void)executeLocked:(void (^)(void))aBlock { + dispatch_sync(_lockQueue, aBlock); +} + +- (void)pushDatabaseBackInPool:(FMDatabase*)db { + + if (!db) { // db can be null if we set an upper bound on the # of databases to create. + return; + } + + [self executeLocked:^() { + + if ([self->_databaseInPool containsObject:db]) { + [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; + } + + [self->_databaseInPool addObject:db]; + [self->_databaseOutPool removeObject:db]; + + }]; +} + +- (FMDatabase*)db { + + __block FMDatabase *db; + + + [self executeLocked:^() { + db = [self->_databaseInPool lastObject]; + + BOOL shouldNotifyDelegate = NO; + + if (db) { + [self->_databaseOutPool addObject:db]; + [self->_databaseInPool removeLastObject]; + } + else { + + if (self->_maximumNumberOfDatabasesToCreate) { + NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; + + if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { + NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); + return; + } + } + + db = [[[self class] databaseClass] databaseWithPath:self->_path]; + shouldNotifyDelegate = YES; + } + + //This ensures that the db is opened before returning +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName]; +#else + BOOL success = [db open]; +#endif + if (success) { + if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { + [db close]; + db = 0x00; + } + else { + //It should not get added in the pool twice if lastObject was found + if (![self->_databaseOutPool containsObject:db]) { + [self->_databaseOutPool addObject:db]; + + if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { + [self->_delegate databasePool:self didAddDatabase:db]; + } + } + } + } + else { + NSLog(@"Could not open up the database at path %@", self->_path); + db = 0x00; + } + }]; + + return db; +} + +- (NSUInteger)countOfCheckedInDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseInPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfCheckedOutDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfOpenDatabases { + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count] + [self->_databaseInPool count]; + }]; + + return count; +} + +- (void)releaseAllDatabases { + [self executeLocked:^() { + [self->_databaseOutPool removeAllObjects]; + [self->_databaseInPool removeAllObjects]; + }]; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { + + FMDatabase *db = [self db]; + + block(db); + + [self pushDatabaseBackInPool:db]; +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + if (useDeferred) { + [db beginDeferredTransaction]; + } + else { + [db beginTransaction]; + } + + + block(db, &shouldRollback); + + if (shouldRollback) { + [db rollback]; + } + else { + [db commit]; + } + + [self pushDatabaseBackInPool:db]; +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + NSError *err = 0x00; + + if (![db startSavePointWithName:name error:&err]) { + [self pushDatabaseBackInPool:db]; + return err; + } + + block(db, &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [db rollbackToSavePointWithName:name error:&err]; + } + [db releaseSavePointWithName:name error:&err]; + + [self pushDatabaseBackInPool:db]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/lib/ios/AirMaps/fmdb/FMDatabaseQueue.h b/lib/ios/AirMaps/fmdb/FMDatabaseQueue.h new file mode 100755 index 000000000..0a8b93816 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabaseQueue.h @@ -0,0 +1,235 @@ +// +// FMDatabaseQueue.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FMDatabase; + +/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. + + Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. + + Instead, use `FMDatabaseQueue`. Here's how to use it: + + First, make your queue. + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; + + Then use it like so: + + [queue inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + FMResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + //… + } + }]; + + An easy way to wrap things up in a transaction can be done like this: + + [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + if (whoopsSomethingWrongHappened) { + *rollback = YES; + return; + } + // etc… + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; + }]; + + `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + + ### See also + + - `` + + @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. + + @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + + */ + +@interface FMDatabaseQueue : NSObject +/** Path of database */ + +@property (atomic, retain, nullable) NSString *path; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy, nullable) NSString *vfsName; + +///---------------------------------------------------- +/// @name Initialization, opening, and closing of queue +///---------------------------------------------------- + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file `NSURL` of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file `NSURL of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Create queue using file URL and specified flags. + + @param url The file `NSURL of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +/** Close database used by queue. */ + +- (void)close; + +/** Interupt pending database operation. */ + +- (void)interrupt; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations on queue. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations on queue, using transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using deferred transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations using save point. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. +// If you need to nest, use FMDatabase's startSavePointWithName:error: instead. +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + +NS_ASSUME_NONNULL_END diff --git a/lib/ios/AirMaps/fmdb/FMDatabaseQueue.m b/lib/ios/AirMaps/fmdb/FMDatabaseQueue.m new file mode 100755 index 000000000..f3f30cf26 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMDatabaseQueue.m @@ -0,0 +1,270 @@ +// +// FMDatabaseQueue.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import "FMDatabaseQueue.h" +#import "FMDatabase.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +/* + + Note: we call [self retain]; before using dispatch_sync, just incase + FMDatabaseQueue is released on another thread and we're in the middle of doing + something in dispatch_sync + + */ + +/* + * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. + * This in turn is used for deadlock detection by seeing if inDatabase: is called on + * the queue's dispatch queue, which should not happen and causes a deadlock. + */ +static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; + +@interface FMDatabaseQueue () { + dispatch_queue_t _queue; + FMDatabase *_db; +} +@end + +@implementation FMDatabaseQueue + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath { + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url { + return [self databaseQueueWithPath:url.path]; +} + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags { + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags { + return [self databaseQueueWithPath:url.path flags:openFlags]; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { + return [self initWithPath:url.path flags:openFlags vfs:vfsName]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + self = [super init]; + + if (self != nil) { + + _db = [[[self class] databaseClass] databaseWithPath:aPath]; + FMDBRetain(_db); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"Could not create database queue for path %@", aPath); + FMDBRelease(self); + return 0x00; + } + + _path = FMDBReturnRetained(aPath); + + _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { + return [self initWithPath:url.path flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)aPath { + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + + +- (void)dealloc { + FMDBRelease(_db); + FMDBRelease(_path); + FMDBRelease(_vfsName); + + if (_queue) { + FMDBDispatchQueueRelease(_queue); + _queue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + [self->_db close]; + FMDBRelease(_db); + self->_db = 0x00; + }); + FMDBRelease(self); +} + +- (void)interrupt { + [[self database] interrupt]; +} + +- (FMDatabase*)database { + if (!_db) { + _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); + FMDBRelease(_db); + _db = 0x00; + return 0x00; + } + } + + return _db; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { +#ifndef NDEBUG + /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue + * and then check it against self to make sure we're not about to deadlock. */ + FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); + assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); +#endif + + FMDBRetain(self); + + dispatch_sync(_queue, ^() { + + FMDatabase *db = [self database]; + block(db); + + if ([db hasOpenResultSets]) { + NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); + +#if defined(DEBUG) && DEBUG + NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + NSLog(@"query: '%@'", [rs query]); + } +#endif + } + }); + + FMDBRelease(self); +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + BOOL shouldRollback = NO; + + if (useDeferred) { + [[self database] beginDeferredTransaction]; + } + else { + [[self database] beginTransaction]; + } + + block([self database], &shouldRollback); + + if (shouldRollback) { + [[self database] rollback]; + } + else { + [[self database] commit]; + } + }); + + FMDBRelease(self); +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + __block NSError *err = 0x00; + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + if ([[self database] startSavePointWithName:name error:&err]) { + + block([self database], &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [[self database] rollbackToSavePointWithName:name error:&err]; + } + [[self database] releaseSavePointWithName:name error:&err]; + + } + }); + FMDBRelease(self); + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/lib/ios/AirMaps/fmdb/FMResultSet.h b/lib/ios/AirMaps/fmdb/FMResultSet.h new file mode 100644 index 000000000..805729109 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMResultSet.h @@ -0,0 +1,467 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +#ifndef __has_feature // Optional. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#endif + +#ifndef NS_RETURNS_NOT_RETAINED +#if __has_feature(attribute_ns_returns_not_retained) +#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) +#else +#define NS_RETURNS_NOT_RETAINED +#endif +#endif + +@class FMDatabase; +@class FMStatement; + +/** Represents the results of executing a query on an ``. + + ### See also + + - `` + */ + +@interface FMResultSet : NSObject + +@property (nonatomic, retain, nullable) FMDatabase *parentDB; + +///----------------- +/// @name Properties +///----------------- + +/** Executed query */ + +@property (atomic, retain, nullable) NSString *query; + +/** `NSMutableDictionary` mapping column names to numeric index */ + +@property (readonly) NSMutableDictionary *columnNameToIndexMap; + +/** `FMStatement` used by result set. */ + +@property (atomic, retain, nullable) FMStatement *statement; + +///------------------------------------ +/// @name Creating and closing database +///------------------------------------ + +/** Create result set from `` + + @param statement A `` to be performed + + @param aDB A `` to be used + + @return A `FMResultSet` on success; `nil` on failure + */ + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; + +/** Close result set */ + +- (void)close; + +///--------------------------------------- +/// @name Iterating through the result set +///--------------------------------------- + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @return `YES` if row successfully retrieved; `NO` if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)next; + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @param outErr A 'NSError' object to receive any error object (if any). + + @return 'YES' if row successfully retrieved; 'NO' if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)nextWithError:(NSError * _Nullable *)outErr; + +/** Did the last call to `` succeed in retrieving another row? + + @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. + + @see next + + @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. + */ + +- (BOOL)hasAnotherRow; + +///--------------------------------------------- +/// @name Retrieving information from result set +///--------------------------------------------- + +/** How many columns in result set + + @return Integer value of the number of columns. + */ + +@property (nonatomic, readonly) int columnCount; + +/** Column index for column name + + @param columnName `NSString` value of the name of the column. + + @return Zero-based index for column. + */ + +- (int)columnIndexForName:(NSString*)columnName; + +/** Column name for column index + + @param columnIdx Zero-based index for column. + + @return columnName `NSString` value of the name of the column. + */ + +- (NSString * _Nullable)columnNameForIndex:(int)columnIdx; + +/** Result set integer value for column. + + @param columnName `NSString` value of the name of the column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumn:(NSString*)columnName; + +/** Result set integer value for column. + + @param columnIdx Zero-based index for column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumnIndex:(int)columnIdx; + +/** Result set `long` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumn:(NSString*)columnName; + +/** Result set long value for column. + + @param columnIdx Zero-based index for column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumnIndex:(int)columnIdx; + +/** Result set `long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumn:(NSString*)columnName; + +/** Result set `long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumnIndex:(int)columnIdx; + +/** Result set `unsigned long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; + +/** Result set `unsigned long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; + +/** Result set `BOOL` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumn:(NSString*)columnName; + +/** Result set `BOOL` value for column. + + @param columnIdx Zero-based index for column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumnIndex:(int)columnIdx; + +/** Result set `double` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumn:(NSString*)columnName; + +/** Result set `double` value for column. + + @param columnIdx Zero-based index for column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumnIndex:(int)columnIdx; + +/** Result set `NSString` value for column. + + @param columnName `NSString` value of the name of the column. + + @return String value of the result set's column. + + */ + +- (NSString * _Nullable)stringForColumn:(NSString*)columnName; + +/** Result set `NSString` value for column. + + @param columnIdx Zero-based index for column. + + @return String value of the result set's column. + */ + +- (NSString * _Nullable)stringForColumnIndex:(int)columnIdx; + +/** Result set `NSDate` value for column. + + @param columnName `NSString` value of the name of the column. + + @return Date value of the result set's column. + */ + +- (NSDate * _Nullable)dateForColumn:(NSString*)columnName; + +/** Result set `NSDate` value for column. + + @param columnIdx Zero-based index for column. + + @return Date value of the result set's column. + + */ + +- (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx; + +/** Result set `NSData` value for column. + + This is useful when storing binary data in table (such as image or the like). + + @param columnName `NSString` value of the name of the column. + + @return Data value of the result set's column. + + */ + +- (NSData * _Nullable)dataForColumn:(NSString*)columnName; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return Data value of the result set's column. + */ + +- (NSData * _Nullable)dataForColumnIndex:(int)columnIdx; + +/** Result set `(const unsigned char *)` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName; + +- (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead"); + +/** Result set `(const unsigned char *)` value for column. + + @param columnIdx Zero-based index for column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + @param columnName Name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectForKeyedSubscript: + */ + +- (id _Nullable)objectForColumn:(NSString*)columnName; + +- (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead"); + +/** Result set object for column. + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectAtIndexedSubscript: + */ + +- (id _Nullable)objectForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[@"employee_name"]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:@"employee_name"]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:@"employee_name"]; + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectForKeyedSubscript:(NSString *)columnName; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[0]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:0]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:0]; + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectAtIndexedSubscript:(int)columnIdx; + +/** Result set `NSData` value for column. + + @param columnName `NSString` value of the name of the column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the +result set, make sure to make a copy of the data first (or just use ``/``) +If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the + result set, make sure to make a copy of the data first (or just use ``/``) + If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; + +/** Is the column `NULL`? + + @param columnIdx Zero-based index for column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIndexIsNull:(int)columnIdx; + +/** Is the column `NULL`? + + @param columnName `NSString` value of the name of the column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIsNull:(NSString*)columnName; + + +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. + + @warning The keys to the dictionary are case sensitive of the column names. + */ + +@property (nonatomic, readonly, nullable) NSDictionary *resultDictionary; + +/** Returns a dictionary of the row results + + @see resultDictionary + + @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! + */ + +- (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead"); + +///----------------------------- +/// @name Key value coding magic +///----------------------------- + +/** Performs `setValue` to yield support for key value observing. + + @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. + + */ + +- (void)kvcMagic:(id)object; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/lib/ios/AirMaps/fmdb/FMResultSet.m b/lib/ios/AirMaps/fmdb/FMResultSet.m new file mode 100644 index 000000000..2231e4761 --- /dev/null +++ b/lib/ios/AirMaps/fmdb/FMResultSet.m @@ -0,0 +1,432 @@ +#import "FMResultSet.h" +#import "FMDatabase.h" +#import "unistd.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () +- (void)resultSetDidClose:(FMResultSet *)resultSet; +@end + +@interface FMResultSet () { + NSMutableDictionary *_columnNameToIndexMap; +} +@end + +@implementation FMResultSet + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { + + FMResultSet *rs = [[FMResultSet alloc] init]; + + [rs setStatement:statement]; + [rs setParentDB:aDB]; + + NSParameterAssert(![statement inUse]); + [statement setInUse:YES]; // weak reference + + return FMDBReturnAutoreleased(rs); +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + + FMDBRelease(_query); + _query = nil; + + FMDBRelease(_columnNameToIndexMap); + _columnNameToIndexMap = nil; + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + [_statement reset]; + FMDBRelease(_statement); + _statement = nil; + + // we don't need this anymore... (i think) + //[_parentDB setInUse:NO]; + [_parentDB resultSetDidClose:self]; + _parentDB = nil; +} + +- (int)columnCount { + return sqlite3_column_count([_statement statement]); +} + +- (NSMutableDictionary *)columnNameToIndexMap { + if (!_columnNameToIndexMap) { + int columnCount = sqlite3_column_count([_statement statement]); + _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] + forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; + } + } + return _columnNameToIndexMap; +} + +- (void)kvcMagic:(id)object { + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + // check for a null row + if (c) { + NSString *s = [NSString stringWithUTF8String:c]; + + [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; + } + } +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (NSDictionary *)resultDict { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; + NSString *columnName = nil; + while ((columnName = [columnNames nextObject])) { + id objectValue = [self objectForColumnName:columnName]; + [dict setObject:objectValue forKey:columnName]; + } + + return FMDBReturnAutoreleased([dict copy]); + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + +#pragma clang diagnostic pop + +- (NSDictionary*)resultDictionary { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; + id objectValue = [self objectForColumnIndex:columnIdx]; + [dict setObject:objectValue forKey:columnName]; + } + + return dict; + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + + + + +- (BOOL)next { + return [self nextWithError:nil]; +} + +- (BOOL)nextWithError:(NSError **)outErr { + + int rc = sqlite3_step([_statement statement]); + + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); + NSLog(@"Database busy"); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { + // all is well, let's return. + } + else if (SQLITE_ERROR == rc) { + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + if (_parentDB) { + *outErr = [_parentDB lastError]; + } + else { + // If 'next' or 'nextWithError' is called after the result set is closed, + // we need to return the appropriate error. + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; + *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; + } + + } + } + else { + // wtf? + NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + + + if (rc != SQLITE_ROW) { + [self close]; + } + + return (rc == SQLITE_ROW); +} + +- (BOOL)hasAnotherRow { + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; +} + +- (int)columnIndexForName:(NSString*)columnName { + columnName = [columnName lowercaseString]; + + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; + + if (n != nil) { + return [n intValue]; + } + + NSLog(@"Warning: I could not find the column named '%@'.", columnName); + + return -1; +} + +- (int)intForColumn:(NSString*)columnName { + return [self intForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (int)intForColumnIndex:(int)columnIdx { + return sqlite3_column_int([_statement statement], columnIdx); +} + +- (long)longForColumn:(NSString*)columnName { + return [self longForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long)longForColumnIndex:(int)columnIdx { + return (long)sqlite3_column_int64([_statement statement], columnIdx); +} + +- (long long int)longLongIntForColumn:(NSString*)columnName { + return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long long int)longLongIntForColumnIndex:(int)columnIdx { + return sqlite3_column_int64([_statement statement], columnIdx); +} + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { + return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { + return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; +} + +- (BOOL)boolForColumn:(NSString*)columnName { + return [self boolForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (BOOL)boolForColumnIndex:(int)columnIdx { + return ([self intForColumnIndex:columnIdx] != 0); +} + +- (double)doubleForColumn:(NSString*)columnName { + return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (double)doubleForColumnIndex:(int)columnIdx { + return sqlite3_column_double([_statement statement], columnIdx); +} + +- (NSString *)stringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + if (!c) { + // null row. + return nil; + } + + return [NSString stringWithUTF8String:c]; +} + +- (NSString*)stringForColumn:(NSString*)columnName { + return [self stringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumn:(NSString*)columnName { + return [self dateForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; +} + + +- (NSData*)dataForColumn:(NSString*)columnName { + return [self dataForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + if (dataBuffer == NULL) { + return nil; + } + + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; +} + + +- (NSData*)dataNoCopyForColumn:(NSString*)columnName { + return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; + + return data; +} + + +- (BOOL)columnIndexIsNull:(int)columnIdx { + return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; +} + +- (BOOL)columnIsNull:(NSString*)columnName { + return [self columnIndexIsNull:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return sqlite3_column_text([_statement statement], columnIdx); +} + +- (const unsigned char *)UTF8StringForColumn:(NSString*)columnName { + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { + return [self UTF8StringForColumn:columnName]; +} + +- (id)objectForColumnIndex:(int)columnIdx { + if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + int columnType = sqlite3_column_type([_statement statement], columnIdx); + + id returnValue = nil; + + if (columnType == SQLITE_INTEGER) { + returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_FLOAT) { + returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_BLOB) { + returnValue = [self dataForColumnIndex:columnIdx]; + } + else { + //default to a string for everything else + returnValue = [self stringForColumnIndex:columnIdx]; + } + + if (returnValue == nil) { + returnValue = [NSNull null]; + } + + return returnValue; +} + +- (id)objectForColumnName:(NSString*)columnName { + return [self objectForColumn:columnName]; +} + +- (id)objectForColumn:(NSString*)columnName { + return [self objectForColumnIndex:[self columnIndexForName:columnName]]; +} + +// returns autoreleased NSString containing the name of the column in the result set +- (NSString*)columnNameForIndex:(int)columnIdx { + return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; +} + +- (id)objectAtIndexedSubscript:(int)columnIdx { + return [self objectForColumnIndex:columnIdx]; +} + +- (id)objectForKeyedSubscript:(NSString *)columnName { + return [self objectForColumn:columnName]; +} + + +@end From cff4e20f36aa97635e92c700f41ba8c4ca2bfc06 Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 17 May 2018 11:39:21 +0200 Subject: [PATCH 02/15] Added changes regarding the comments of @h3ll0w0rld123 from here: https://github.com/react-community/react-native-maps/pull/2208#discussion_r182597094 --- .../android/react/maps/AirMapMbTile.java | 21 ++++++++++--- lib/ios/AirMaps/AIRMapMbTileOverlay.m | 31 +++++++++++-------- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index 7fd861e52..00987a496 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -51,21 +51,32 @@ private byte[] readTileImage(int x, int y, int zoom) { String rawQuery = "SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y}"; try { + byte[] tile = null; SQLiteDatabase offlineDataDatabase = SQLiteDatabase.openDatabase(this.pathTemplate, null, SQLiteDatabase.OPEN_READONLY); String query = rawQuery.replace("{x}", Integer.toString(x)) .replace("{y}", Integer.toString(y)) .replace("{z}", Integer.toString(zoom)); Cursor cursor = offlineDataDatabase.rawQuery(query, null); if(cursor.moveToFirst()){ - byte[] tile = cursor.getBlob(5); - cursor.close(); - offlineDataDatabase.close(); - return tile; + tile = cursor.getBlob(5); } + cursor.close(); offlineDataDatabase.close(); - return null; + return tile; + } catch (SQLiteCantOpenDatabaseException e) { + e.printStackTrace(); + throw e; + } catch (SQLiteDatabaseCorruptException e) { + e.printStackTrace(); + throw e; + } catch (SQLiteDatabaseLockedException e) { + e.printStackTrace(); + throw e; } catch (Exception e) { e.printStackTrace(); + throw e; + } finally { + offlineDataDatabase.close(); return null; } } diff --git a/lib/ios/AirMaps/AIRMapMbTileOverlay.m b/lib/ios/AirMaps/AIRMapMbTileOverlay.m index 4a87eab6f..1eb6906b5 100644 --- a/lib/ios/AirMaps/AIRMapMbTileOverlay.m +++ b/lib/ios/AirMaps/AIRMapMbTileOverlay.m @@ -18,20 +18,25 @@ @implementation AIRMapMbTileOverlay -(void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *, NSError *))result { - FMDatabase *offlineDataDatabase = [FMDatabase databaseWithPath:self.URLTemplate]; - [offlineDataDatabase open]; - NSMutableString *query = [NSMutableString stringWithString: @"SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y};"]; - [query replaceCharactersInRange: [query rangeOfString: @"{z}"] withString:[NSString stringWithFormat:@"%li", path.z]]; - [query replaceCharactersInRange: [query rangeOfString: @"{x}"] withString:[NSString stringWithFormat:@"%li", path.x]]; - [query replaceCharactersInRange: [query rangeOfString: @"{y}"] withString:[NSString stringWithFormat:@"%li", path.y]]; - FMResultSet *databaseResult = [offlineDataDatabase executeQuery:query]; - if ([databaseResult next]) { - NSData *tile = [databaseResult dataForColumn:@"tile_data"]; - [offlineDataDatabase close]; - result(tile,nil); + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:self.URLTemplate]) { + FMDatabase *offlineDataDatabase = [FMDatabase databaseWithPath:self.URLTemplate]; + [offlineDataDatabase open]; + NSMutableString *query = [NSMutableString stringWithString: @"SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y};"]; + [query replaceCharactersInRange: [query rangeOfString: @"{z}"] withString:[NSString stringWithFormat:@"%li", path.z]]; + [query replaceCharactersInRange: [query rangeOfString: @"{x}"] withString:[NSString stringWithFormat:@"%li", path.x]]; + [query replaceCharactersInRange: [query rangeOfString: @"{y}"] withString:[NSString stringWithFormat:@"%li", path.y]]; + FMResultSet *databaseResult = [offlineDataDatabase executeQuery:query]; + if ([databaseResult next]) { + NSData *tile = [databaseResult dataForColumn:@"tile_data"]; + [offlineDataDatabase close]; + result(tile,nil); + } else { + [offlineDataDatabase close]; + result(nil,nil); + } } else { - [offlineDataDatabase close]; - result(nil,nil); + NSLog(@"Database not found. Wrong path."); } } From d539adc38c8af9c21afb0ce00d966fb01881543e Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 17 May 2018 11:58:56 +0200 Subject: [PATCH 03/15] Added whitespaces --- .../main/java/com/airbnb/android/react/maps/AirMapMbTile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index 00987a496..60fbfc949 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -57,7 +57,7 @@ private byte[] readTileImage(int x, int y, int zoom) { .replace("{y}", Integer.toString(y)) .replace("{z}", Integer.toString(zoom)); Cursor cursor = offlineDataDatabase.rawQuery(query, null); - if(cursor.moveToFirst()){ + if (cursor.moveToFirst()) { tile = cursor.getBlob(5); } cursor.close(); From 78842e899da509673d8cf23b9e41157093a58b13 Mon Sep 17 00:00:00 2001 From: Christoph Date: Thu, 17 May 2018 13:16:44 +0200 Subject: [PATCH 04/15] Hotfix: Imported exceptions. Changed database.close() --- .../main/java/com/airbnb/android/react/maps/AirMapMbTile.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index 60fbfc949..d6bca4cba 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -12,6 +12,9 @@ import android.os.Environment; import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteCantOpenDatabaseException; +import android.database.sqlite.SQLiteDatabaseCorruptException; +import android.database.sqlite.SQLiteDatabaseLockedException; import android.database.Cursor; /** @@ -76,7 +79,6 @@ private byte[] readTileImage(int x, int y, int zoom) { e.printStackTrace(); throw e; } finally { - offlineDataDatabase.close(); return null; } } From f09a37a7fe9420e7c63c7637af5ac49d8e6ed8f2 Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 09:39:18 +0200 Subject: [PATCH 05/15] Hotfix: Removed the finally statemend. Resulted in always returning null --- .../java/com/airbnb/android/react/maps/AirMapMbTile.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index d6bca4cba..3dff11067 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -68,17 +68,15 @@ private byte[] readTileImage(int x, int y, int zoom) { return tile; } catch (SQLiteCantOpenDatabaseException e) { e.printStackTrace(); - throw e; + return null; } catch (SQLiteDatabaseCorruptException e) { e.printStackTrace(); - throw e; + return null; } catch (SQLiteDatabaseLockedException e) { e.printStackTrace(); - throw e; + return null; } catch (Exception e) { e.printStackTrace(); - throw e; - } finally { return null; } } From 37aba13d1d99eac92686aae4f767b1a5e2edb423 Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 09:53:39 +0200 Subject: [PATCH 06/15] Removed repetition of returns. Moved everything into finally statement instead --- .../com/airbnb/android/react/maps/AirMapMbTile.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index 3dff11067..a74b34976 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -52,9 +52,8 @@ public void setTileSize(int tileSize) { private byte[] readTileImage(int x, int y, int zoom) { String rawQuery = "SELECT * FROM map INNER JOIN images ON map.tile_id = images.tile_id WHERE map.zoom_level = {z} AND map.tile_column = {x} AND map.tile_row = {y}"; - + byte[] tile = null; try { - byte[] tile = null; SQLiteDatabase offlineDataDatabase = SQLiteDatabase.openDatabase(this.pathTemplate, null, SQLiteDatabase.OPEN_READONLY); String query = rawQuery.replace("{x}", Integer.toString(x)) .replace("{y}", Integer.toString(y)) @@ -65,19 +64,16 @@ private byte[] readTileImage(int x, int y, int zoom) { } cursor.close(); offlineDataDatabase.close(); - return tile; } catch (SQLiteCantOpenDatabaseException e) { e.printStackTrace(); - return null; } catch (SQLiteDatabaseCorruptException e) { e.printStackTrace(); - return null; } catch (SQLiteDatabaseLockedException e) { e.printStackTrace(); - return null; } catch (Exception e) { e.printStackTrace(); - return null; + } finally { + return tile; } } } From a4b5460d37f901a2befd36481461412f18ac0c3c Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 09:54:22 +0200 Subject: [PATCH 07/15] Throwing exceptions --- .../main/java/com/airbnb/android/react/maps/AirMapMbTile.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java index a74b34976..0c948adef 100644 --- a/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java +++ b/lib/android/src/main/java/com/airbnb/android/react/maps/AirMapMbTile.java @@ -66,12 +66,16 @@ private byte[] readTileImage(int x, int y, int zoom) { offlineDataDatabase.close(); } catch (SQLiteCantOpenDatabaseException e) { e.printStackTrace(); + throw e; } catch (SQLiteDatabaseCorruptException e) { e.printStackTrace(); + throw e; } catch (SQLiteDatabaseLockedException e) { e.printStackTrace(); + throw e; } catch (Exception e) { e.printStackTrace(); + throw e; } finally { return tile; } From 08869622f73376c1d19845a44a8ef4292b7bf946 Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 10:27:28 +0200 Subject: [PATCH 08/15] Added MapView.MbTile to Readme. Inclduded the component in the Readme --- README.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/README.md b/README.md index e6e08cf7f..27aaaf876 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,39 @@ For Android: LocalTile is still just overlay over original map tiles. It means t See [OSM Wiki](https://wiki.openstreetmap.org/wiki/Category:Tile_downloading) for how to download tiles for offline usage. + +#### Tile Overlay using MbTile + +Tiles can be stored locally in a MBTiles database on the device using xyz tiling scheme. The locally stored tiles can be displayed as a tile overlay. This can be used for displaying maps offline. Manging many tiles in a database is especially useful if larger areas are covered by an offline map. Keeping all the files locally and "raw" on the device most likely results in bad performance as well as troublesome datahandling. Please make sure that your database follows the MBTiles [specifications](https://github.com/mapbox/mbtiles-spec). This only works with tiles stored in the [xyz scheme](https://gist.github.com/tmcw/4954720) as used by Google, OSM, MapBox, ... + +```jsx +import MapView from 'react-native-maps'; + + + + +``` + +For Android: LocalTile is still just overlay over original map tiles. It means that if device is online, underlying tiles will be still downloaded. If original tiles download/display is not desirable set mapType to 'none'. For example: +``` + +``` + ### Customizing the map style Create the json object, or download a generated one from the [google style generator](https://mapstyle.withgoogle.com/). From 304c66da0cb8bb236c82fc6bdbd36481437398c3 Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 10:30:10 +0200 Subject: [PATCH 09/15] Added example file --- example/examples/MbTileOverlay.js | 86 +++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 example/examples/MbTileOverlay.js diff --git a/example/examples/MbTileOverlay.js b/example/examples/MbTileOverlay.js new file mode 100644 index 000000000..71babf194 --- /dev/null +++ b/example/examples/MbTileOverlay.js @@ -0,0 +1,86 @@ +import React, { Component } from 'react'; +import { + StyleSheet, + View, + Dimensions, + TouchableOpacity, + Text, + Platform, +} from 'react-native'; +import MapView from 'react-native-maps'; + +const { width, height } = Dimensions.get('window'); + +const ASPECT_RATIO = width / height; +const LATITUDE = 23.736906; +const LONGITUDE = 90.397768; +const LATITUDE_DELTA = 0.022; +const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; +const SPACE = 0.01; + +type Props = {}; +export default class App extends Component { + constructor(props) { + super(props); + + this.state = { + offlineMap: false + }; + } + + _toggleOfflineMap = () => { + this.setState({ + offlineMap: !this.state.offlineMap + }); + } + + render() { + return ( + + + {this.state.offlineMap ? : null} + + this._toggleOfflineMap()}> + {this.state.offlineMap ? "Switch to Online Map" : "Switch to Offline Map"} + + + ) + } +} + +const styles = StyleSheet.create({ + container: { + ...StyleSheet.absoluteFillObject, + alignItems: "center", + }, + button: { + position: "absolute", + bottom: 20, + backgroundColor: "lightblue", + zIndex: 999999, + height: 50, + width: width / 2, + borderRadius: width / 2, + justifyContent: "center", + alignItems: "center", + }, + map: { + ...StyleSheet.absoluteFillObject, + } +}); \ No newline at end of file From 95f4db13eeab7538960da235129bc13f77c518fb Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 18 May 2018 10:32:04 +0200 Subject: [PATCH 10/15] Included more information in Readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 27aaaf876..c5f02e97a 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,7 @@ See [OSM Wiki](https://wiki.openstreetmap.org/wiki/Category:Tile_downloading) fo #### Tile Overlay using MbTile -Tiles can be stored locally in a MBTiles database on the device using xyz tiling scheme. The locally stored tiles can be displayed as a tile overlay. This can be used for displaying maps offline. Manging many tiles in a database is especially useful if larger areas are covered by an offline map. Keeping all the files locally and "raw" on the device most likely results in bad performance as well as troublesome datahandling. Please make sure that your database follows the MBTiles [specifications](https://github.com/mapbox/mbtiles-spec). This only works with tiles stored in the [xyz scheme](https://gist.github.com/tmcw/4954720) as used by Google, OSM, MapBox, ... +Tiles can be stored locally in a MBTiles database on the device using xyz tiling scheme. The locally stored tiles can be displayed as a tile overlay. This can be used for displaying maps offline. Manging many tiles in a database is especially useful if larger areas are covered by an offline map. Keeping all the files locally and "raw" on the device most likely results in bad performance as well as troublesome datahandling. Please make sure that your database follows the MBTiles [specifications](https://github.com/mapbox/mbtiles-spec). This only works with tiles stored in the [xyz scheme](https://gist.github.com/tmcw/4954720) as used by Google, OSM, MapBox, ... Make sure to include the ending .mbtiles when you pass your pathTemplate. ```jsx import MapView from 'react-native-maps'; From 79181c14daf1f510198b377c4843d68fdddd634b Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 19 Jul 2018 09:12:20 +0200 Subject: [PATCH 11/15] Edited example file accodring to linter errors in Pull Request --- example/examples/MbTileOverlay.js | 44 +++++++++++++++++-------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/example/examples/MbTileOverlay.js b/example/examples/MbTileOverlay.js index 71babf194..303c3ff0b 100644 --- a/example/examples/MbTileOverlay.js +++ b/example/examples/MbTileOverlay.js @@ -16,7 +16,7 @@ const LATITUDE = 23.736906; const LONGITUDE = 90.397768; const LATITUDE_DELTA = 0.022; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; -const SPACE = 0.01; + type Props = {}; export default class App extends Component { @@ -24,20 +24,21 @@ export default class App extends Component { super(props); this.state = { - offlineMap: false + offlineMap: false, }; } _toggleOfflineMap = () => { this.setState({ - offlineMap: !this.state.offlineMap + offlineMap: !this.state.offlineMap, }); } render() { return ( - + { longitudeDelta: LONGITUDE_DELTA, }} loadingEnabled - loadingIndicatorColor="#666666" - loadingBackgroundColor="#eeeeee" - mapType={Platform.OS == "android" && this.state.offlineMap ? "none" : "standard"}> - {this.state.offlineMap ? : null} + loadingIndicatorColor='#666666' + loadingBackgroundColor='#eeeeee' + mapType={Platform.OS === 'android' && this.state.offlineMap ? 'none' : 'standard'} + > + {this.state.offlineMap ? + : null} this._toggleOfflineMap()}> - {this.state.offlineMap ? "Switch to Online Map" : "Switch to Offline Map"} + {this.state.offlineMap ? 'Switch to Online Map' : 'Switch to Offline Map'} - ) + ); } } const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, - alignItems: "center", + alignItems: 'center', }, button: { - position: "absolute", + position: 'absolute', bottom: 20, - backgroundColor: "lightblue", + backgroundColor: 'lightblue', zIndex: 999999, height: 50, width: width / 2, borderRadius: width / 2, - justifyContent: "center", - alignItems: "center", + justifyContent: 'center', + alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, - } -}); \ No newline at end of file + }, +}); From 1e3068bc1fdf554baf6eb30fd287a352e5dc8884 Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 19 Jul 2018 09:22:27 +0200 Subject: [PATCH 12/15] Edited index.d.ts according to merge conflicts in Pull Request. Had to change a few lines --- index.d.ts | 267 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 184 insertions(+), 83 deletions(-) diff --git a/index.d.ts b/index.d.ts index ebc7f4a4a..f380d3c15 100755 --- a/index.d.ts +++ b/index.d.ts @@ -1,16 +1,24 @@ declare module "react-native-maps" { + import * as React from 'react'; - + import { + Animated, + ImageRequireSource, + ImageURISource, + NativeSyntheticEvent, + ViewProperties + } from 'react-native'; + export interface Region { - latitude: number - longitude: number - latitudeDelta: number - longitudeDelta: number + latitude: number; + longitude: number; + latitudeDelta: number; + longitudeDelta: number; } - + export interface LatLng { - latitude: number - longitude: number + latitude: number; + longitude: number; } export interface Point { @@ -147,10 +155,11 @@ declare module "react-native-maps" { export interface KmlMapEvent extends NativeSyntheticEvent<{ markers: KmlMarker[] }> { } - export interface MapViewProps { - provider?: 'google'; - style: any; - customMapStyle?: any[]; + type MapTypes = 'standard' | 'satellite' | 'hybrid' | 'terrain' | 'none' | 'mutedStandard'; + + export interface MapViewProps extends ViewProperties { + provider?: 'google' | null; + customMapStyle?: MapStyleElement[]; customMapStyleString?: string; showsUserLocation?: boolean; userLocationAnnotationTitle?: string; @@ -163,8 +172,8 @@ declare module "react-native-maps" { rotateEnabled?: boolean; cacheEnabled?: boolean; loadingEnabled?: boolean; - loadingBackgroundColor?: any; - loadingIndicatorColor?: any; + loadingBackgroundColor?: string; + loadingIndicatorColor?: string; scrollEnabled?: boolean; pitchEnabled?: boolean; toolbarEnabled?: boolean; @@ -174,84 +183,130 @@ declare module "react-native-maps" { showsTraffic?: boolean; showsIndoors?: boolean; showsIndoorLevelPicker?: boolean; - mapType?: 'standard' | 'satellite' | 'hybrid' | 'terrain' | 'none' | 'mutedStandard'; - region?: { latitude: number; longitude: number; latitudeDelta: number; longitudeDelta: number; }; - initialRegion?: { latitude: number; longitude: number; latitudeDelta: number; longitudeDelta: number; }; + mapType?: MapTypes; + region?: Region; + initialRegion?: Region; liteMode?: boolean; + mapPadding?: EdgePadding; maxDelta?: number; minDelta?: number; - legalLabelInsets?: any; - onChange?: Function; - onMapReady?: Function; + legalLabelInsets?: EdgeInsets; + + onMapReady?: () => void; + onKmlReady?: (values: KmlMapEvent) => void; onRegionChange?: (region: Region) => void; onRegionChangeComplete?: (region: Region) => void; - onPress?: (value: { coordinate: LatLng, position: Point }) => void; - onLayout?: Function; - onLongPress?: (value: { coordinate: LatLng, position: Point }) => void; - onPanDrag?: (value: {coordinate: LatLng, position: Point }) => void; - onMarkerPress?: Function; - onMarkerSelect?: Function; - onMarkerDeselect?: Function; - onCalloutPress?: Function; - onMarkerDragStart?: (value: { coordinate: LatLng, position: Point }) => void; - onMarkerDrag?: (value: { coordinate: LatLng, position: Point }) => void; - onMarkerDragEnd?: (value: { coordinate: LatLng, position: Point }) => void; + onPress?: (event: MapEvent) => void; + onLongPress?: (event: MapEvent) => void; + onUserLocationChange?: (event: EventUserLocation) => void; + onPanDrag?: (event: MapEvent) => void; + onPoiClick?: (event: MapEvent<{ placeId: string, name: string }>) => void; + onMarkerPress?: (event: MapEvent<{ action: 'marker-press', id: string }>) => void; + onMarkerSelect?: (event: MapEvent<{ action: 'marker-select', id: string }>) => void; + onMarkerDeselect?: (event: MapEvent<{ action: 'marker-deselect', id: string }>) => void; + onCalloutPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; + onMarkerDragStart?: (event: MapEvent) => void; + onMarkerDrag?: (event: MapEvent) => void; + onMarkerDragEnd?: (event: MapEvent) => void; + minZoomLevel?: number; maxZoomLevel?: number; + kmlSrc?: string; } export default class MapView extends React.Component { - static Animated: any; - static AnimatedRegion: any; + animateToNavigation(location: LatLng, bearing: number, angle: number, duration?: number): void; animateToRegion(region: Region, duration?: number): void; animateToCoordinate(latLng: LatLng, duration?: number): void; animateToBearing(bearing: number, duration?: number): void; animateToViewingAngle(angle: number, duration?: number): void; fitToElements(animated: boolean): void; fitToSuppliedMarkers(markers: string[], animated: boolean): void; - fitToCoordinates(coordinates?: LatLng[], options?:{}): void; + fitToCoordinates(coordinates?: LatLng[], options?: { edgePadding?: EdgePadding, animated?: boolean }): void; setMapBoundaries(northEast: LatLng, southWest: LatLng): void; + takeSnapshot(options?: SnapshotOptions): Promise; } - export type LineCapType = 'butt' | 'round' | 'square'; - export type LineJoinType = 'miter' | 'round' | 'bevel'; + export class MapViewAnimated extends MapView { + } - export interface MarkerProps { + // ======================================================================= + // Marker + // ======================================================================= + + export interface MarkerProps extends ViewProperties { identifier?: string; reuseIdentifier?: string; title?: string; description?: string; - image?: any; + image?: ImageURISource | ImageRequireSource; opacity?: number; pinColor?: string; - coordinate: { latitude: number; longitude: number }; - centerOffset?: { x: number; y: number }; - calloutOffset?: { x: number; y: number }; - anchor?: { x: number; y: number }; - calloutAnchor?: { x: number; y: number }; + coordinate: LatLng | AnimatedRegion; + centerOffset?: Point; + calloutOffset?: Point; + anchor?: Point; + calloutAnchor?: Point; flat?: boolean; draggable?: boolean; - onPress?: (value: { coordinate: LatLng, position: Point }) => void; - onSelect?: (value: { coordinate: LatLng, position: Point }) => void; - onDeselect?: (value: { coordinate: LatLng, position: Point }) => void; - onCalloutPress?: Function; - onDragStart?: (value: { coordinate: LatLng, position: Point }) => void; - onDrag?: (value: { coordinate: LatLng, position: Point }) => void; - onDragEnd?: (value: { coordinate: LatLng, position: Point }) => void; - zIndex?: number; - style?: any; - rotation?: number; tracksViewChanges?: boolean tracksInfoWindowChanges?: boolean + stopPropagation?: boolean + onPress?: (event: MapEvent<{ action: 'marker-press', id: string }>) => void; + onSelect?: (event: MapEvent<{ action: 'marker-select', id: string }>) => void; + onDeselect?: (event: MapEvent<{ action: 'marker-deselect', id: string }>) => void; + onCalloutPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; + onDragStart?: (event: MapEvent) => void; + onDrag?: (event: MapEvent) => void; + onDragEnd?: (event: MapEvent) => void; + + rotation?: number; + zIndex?: number; + } + + export class Marker extends React.Component { + /** + * Shows the callout for this marker + */ + showCallout(): void; + /** + * Hides the callout for this marker + */ + hideCallout(): void; + /** + * Animates marker movement. + * __Android only__ + */ + animateMarkerToCoordinate(coordinate: LatLng, duration?: number): void; + } + + export class MarkerAnimated extends Marker { } - export interface MapPolylineProps { - coordinates: { latitude: number; longitude: number; }[]; - onPress?: Function; + // ======================================================================= + // Callout + // ======================================================================= + + export interface MapCalloutProps extends ViewProperties { + tooltip?: boolean; + onPress?: (event: MapEvent<{ action: 'callout-press' }>) => void; + } + + export class Callout extends React.Component { + } + + // ======================================================================= + // Polyline + // ======================================================================= + + export interface MapPolylineProps extends ViewProperties { + coordinates: LatLng[]; + onPress?: (event: MapEvent) => void; tappable?: boolean; fillColor?: string; strokeWidth?: number; strokeColor?: string; + strokeColors?: string[]; zIndex?: number; lineCap?: LineCapType; lineJoin?: LineJoinType; @@ -261,10 +316,17 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export interface MapPolygonProps { - coordinates: { latitude: number; longitude: number; }[]; - holes?: { latitude: number; longitude: number; }[][]; - onPress?: Function; + export class Polyline extends React.Component { + } + + // ======================================================================= + // Polygon + // ======================================================================= + + export interface MapPolygonProps extends ViewProperties { + coordinates: LatLng[]; + holes?: LatLng[][]; + onPress?: (event: MapEvent) => void; tappable?: boolean; strokeWidth?: number; strokeColor?: string; @@ -278,10 +340,17 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export interface MapCircleProps { - center: { latitude: number; longitude: number }; + export class Polygon extends React.Component { + } + + // ======================================================================= + // Circle + // ======================================================================= + + export interface MapCircleProps extends ViewProperties { + center: LatLng; radius: number; - onPress?: Function; + onPress?: (event: MapEvent) => void; strokeWidth?: number; strokeColor?: string; fillColor?: string; @@ -293,39 +362,71 @@ declare module "react-native-maps" { lineDashPattern?: number[]; } - export interface MapUrlTileProps { + export class Circle extends React.Component { + } + + // ======================================================================= + // UrlTile, LocalTile & MbTile + // ======================================================================= + + export interface MapUrlTileProps extends ViewProperties { urlTemplate: string; + maximumZ?: number; zIndex?: number; } - export interface MapLocalTileProps { + export class UrlTile extends React.Component { + } + + export interface MapLocalTileProps extends ViewProperties { pathTemplate: string; - tileSize: number; + tileSize?: number; zIndex?: number; } - export interface MapMbTileProps { + export class LocalTile extends React.Component { + } + + export interface MapMbTileProps extends ViewProperties { pathTemplate: string; tileSize: number; zIndex?: number; } - export interface MapCalloutProps { - tooltip?: boolean; - onPress?: Function; - style?: any; + export class MbTile extends React.Component { } - export class Marker extends React.Component { - showCallout(): void; - hideCallout(): void; - animateMarkerToCoordinate(coordinate: LatLng, duration: number): void; - } - export class Polyline extends React.Component { } - export class Polygon extends React.Component { } - export class Circle extends React.Component { } - export class UrlTile extends React.Component { } - export class LocalTile extends React.Component { } - export class MbTile extends React.Component { } - export class Callout extends React.Component { } + // ======================================================================= + // Overlay + // ======================================================================= + + type Coordinate = [number, number] + + export interface MapOverlayProps extends ViewProperties { + image?: ImageURISource | ImageRequireSource; + bounds: [Coordinate, Coordinate]; + } + + export class Overlay extends React.Component { + } + + export class OverlayAnimated extends Overlay { + } + + // ======================================================================= + // Constants + // ======================================================================= + + export const MAP_TYPES: { + STANDARD: MapTypes, + SATELLITE: MapTypes, + HYBRID: MapTypes, + TERRAIN: MapTypes, + NONE: MapTypes, + MUTEDSTANDARD: MapTypes, + } + + export const PROVIDER_DEFAULT: null; + export const PROVIDER_GOOGLE: 'google'; + } From a170a9e0e35ad2cbc7f9f2d76e0b6d1f62152f59 Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 19 Jul 2018 09:32:59 +0200 Subject: [PATCH 13/15] Edited example file according to linter errors in merge request --- example/examples/MbTileOverlay.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/example/examples/MbTileOverlay.js b/example/examples/MbTileOverlay.js index 303c3ff0b..486548321 100644 --- a/example/examples/MbTileOverlay.js +++ b/example/examples/MbTileOverlay.js @@ -36,8 +36,8 @@ export default class App extends Component { render() { return ( - { longitudeDelta: LONGITUDE_DELTA, }} loadingEnabled - loadingIndicatorColor='#666666' + loadingIndicatorColor="#666666" loadingBackgroundColor='#eeeeee' mapType={Platform.OS === 'android' && this.state.offlineMap ? 'none' : 'standard'} > - {this.state.offlineMap ? + {this.state.offlineMap ? { this._toggleOfflineMap()}> + onPress={() => this._toggleOfflineMap()} + > {this.state.offlineMap ? 'Switch to Online Map' : 'Switch to Offline Map'} From 7603cfa819f9362de4ede42ad5ab5bd2335cafb9 Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 19 Jul 2018 09:36:56 +0200 Subject: [PATCH 14/15] Edited example file according to linter errors in merge request. I am starting not to like Travis... --- example/examples/MbTileOverlay.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/example/examples/MbTileOverlay.js b/example/examples/MbTileOverlay.js index 486548321..3499a53bf 100644 --- a/example/examples/MbTileOverlay.js +++ b/example/examples/MbTileOverlay.js @@ -49,14 +49,14 @@ export default class App extends Component { }} loadingEnabled loadingIndicatorColor="#666666" - loadingBackgroundColor='#eeeeee' + loadingBackgroundColor="#eeeeee" mapType={Platform.OS === 'android' && this.state.offlineMap ? 'none' : 'standard'} > {this.state.offlineMap ? - : null} + : null} { > {this.state.offlineMap ? 'Switch to Online Map' : 'Switch to Offline Map'} - + ); } } @@ -72,18 +72,18 @@ export default class App extends Component { const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, - alignItems: 'center', + alignItems: "center", }, button: { - position: 'absolute', + position: "absolute", bottom: 20, - backgroundColor: 'lightblue', + backgroundColor: "lightblue", zIndex: 999999, height: 50, width: width / 2, borderRadius: width / 2, - justifyContent: 'center', - alignItems: 'center', + justifyContent: "center", + alignItems: "center", }, map: { ...StyleSheet.absoluteFillObject, From 37455e82745e80a42d0eeeacacb522507d5df00b Mon Sep 17 00:00:00 2001 From: Christoph Lambio Date: Thu, 19 Jul 2018 09:39:01 +0200 Subject: [PATCH 15/15] Edited example file according to linter errors in merge request. I am starting not to like Travis... --- example/examples/MbTileOverlay.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/example/examples/MbTileOverlay.js b/example/examples/MbTileOverlay.js index 3499a53bf..cfb185147 100644 --- a/example/examples/MbTileOverlay.js +++ b/example/examples/MbTileOverlay.js @@ -72,18 +72,18 @@ export default class App extends Component { const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, - alignItems: "center", + alignItems: 'center', }, button: { - position: "absolute", + position: 'absolute', bottom: 20, - backgroundColor: "lightblue", + backgroundColor: 'lightblue', zIndex: 999999, height: 50, width: width / 2, borderRadius: width / 2, - justifyContent: "center", - alignItems: "center", + justifyContent: 'center', + alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject,